Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have an optimisation issue I would like to execute the subquery first
```
EXPLAIN
SELECT *
FROM `References_galaxia`
, Link_galaxia
WHERE linkReferenced IN ( SELECT id
FROM Link_galaxia
WHERE idConceptStart IN (616269,616268,615721)
... | A query such as the following would appear to be more optimal:
```
SELECT columns, I, actually, want
FROM `References_galaxia` r
JOIN Link_galaxia x
ON x.id = r.linkreferenced
JOIN Link_galaxia y
ON y.id = r.linkReferenced
WHERE r.idConcept IN (416,36053,36088,36037)
AND y.idConceptStart IN (616269,... | ```
SELECT *
FROM `References_galaxia`
, Link_galaxia
WHERE `References_galaxia`.linkReferenced = Link_galaxia.id
AND `References_galaxia`.idConcept IN (416,36053,36088,36037)
AND Link_galaxia.idConceptStart IN (616269,616268,615721)
AND Link_galaxia.idConceptLink = 315
AND Link_galaxia.idConce... | SQL subqueries optimisation, how to execute subquery first | [
"",
"mysql",
"sql",
"subquery",
""
] |
It's hard to explain my question, but here is the issue. I have a table of 350k records. The table is filled with skus and other part information. There are many rows that have the same sku. For example there are 5 rows with the sku 45666. I need to put a unique identifier on each of these. e.g 45666~1, 45666~2, etc...... | Give this query a try (please don't run this on production data before testing or backing up):
```
update t
set t.sku = t.sku + '~' + cast(t.RowNumber as varchar)
from (
select sku, row_number() over(partition by sku order by sku) as RowNumber
from whiproducts) t
``` | How about appending on a unique GUID. Then you can just do things with a single update statement, no looping at all.
`UPDATE whipproducts
SET number = number + '_' + cast(NEWID() as varchar(100))` | How can I append a unique identifier onto rows with same column value | [
"",
"sql",
"powershell",
"unique",
"identifier",
""
] |
I'm using the chinook database and sqlite3. My goal is to return a list of invoices with the invoice id, invoice date and the number of items on the invoice for a specific customer. The first two are pretty simple,
```
SELECT InvoiceId, InvoiceDate
FROM invoices
WHERE CustomerId = 2;
```
returns:
```
1 |2009-01-0... | You need an inner join on your query; it will look something like this:
```
SELECT
invoices.InvoiceId, invoices.InvoiceDate,
COUNT(DISTINCT(items.ID)) AS Items
FROM
invoices
JOIN
invoice_items AS items ON invoices.ID = itemsID
GROUP BY invoices.InvoiceId
```
Of course I'm guessing the names of you... | Try a subquery like the following:
`select invoiceid, invoicedate,
(select count(*) from invoice_items where invoiceid = i.invoiceid) as CountInvoiceItems
from invoices`
to get all the results, otherwise you can add your where clause back in for just invoice 12. | Get information about an invoice and return the number of invoice items on it with a single SELECT comand | [
"",
"sql",
"sqlite",
""
] |
I am trying to do SQL Injection testing but I am currently testing a command line that separates parameters by spaces, so I'm trying to write a sql statement without any spaces. I've gotten it down to:
`create table"aab"("id"int,"notes"varchar(100))`
But I cannot figure out how to get rid of the space between CREATE a... | This is not possible, you have to check every argument to make sure they are as intended.
If they are supposed to be numbers, make sure they are numbers, is they are supposed to be a string that may contain specific caracters (like ' or ,) you should escape them when executing the request.
There should be a dedicated... | You can write comments between lines instead of spaces in many cases. So /\*\*/ instead of spaces. | Can you write a sql statement without spaces between keywords | [
"",
"sql",
"sql-server",
"database",
"security",
""
] |
Suppose I have a table like:
```
id | parentId | name
1 NULL A
2 1 B
3 2 C
4 1 E
5 3 E
```
I am trying to write a scalar function I can call as:
`SELECT dbo.GetId('A/B/C/E')` which would produce "5" if we us... | I think I have it based on @SeanLange's recommendation to use a recursive CTE (above in the comments):
```
CREATE FUNCTION GetID
(
@path VARCHAR(MAX)
)
/* TEST:
SELECT dbo.GetID('A/B/C/E')
*/
RETURNS INT
AS
BEGIN
DECLARE @ID INT;
WITH cte AS (
SELECT p.id ,
p.parentId ,
... | `CTE` version is not optimized way to get the hierarchical data. ([Refer MSDN Blog](https://blogs.msdn.microsoft.com/sqlcat/2011/04/28/optimize-recursive-cte-query/))
You should do something like as mentioned below. It's tested for 10 millions of records and is 300 times faster than CTE version :)
```
Declare @table ... | How to traverse a path in a table with id & parentId? | [
"",
"sql",
"sql-server",
"hierarchical-data",
"recursive-query",
""
] |
I have two tables:
`table1`: (ID, Code, Name)
`table2`: (ID, Code, Name)
with same columns
I want to to insert data from table1 to table2 or update columns if that exists in table2 (table1.ID = table2.ID)
What is the simple way to do this?
WITH OUT **MERGE** | ```
Merge table2 as target
using table1 as source
on
target.id=source.id
When matched
Then
update
set target.id=source.id,
target.name=source.name
When not matched by Target Then
INSERT (id, name) VALUES (id, name);
```
There are some issues with Merge statement,so it should be used with [caution](https://www.m... | ```
MERGE table2 t2
USING table1 t1
ON t1.ID = t2.ID
WHEN MATCHED THEN
UPDATE
SET t2.Code = t1.Code, t2.Name = t1.Name
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, Name, Code)
VALUES (t1.ID, t1.Name, t1.Code);
``` | Update and insert to one table from another | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
how to combine this two queries without giving me the same output ?
the first query is :
```
select vwemployee.directorateName , count(vwemployeeCourse.employeeId) as t1
from vwemployee , vwemployeeCourse
where vwemployee.directorateName = vwemployeeCourse.directorateName
GROUP BY vwemployee.directorateNam... | If you are purposely using a employeeCourse instead of vwemployeeCourse in the second query I would use the following. I use a full outer join in case some directorates are in one table/view and not the other. If it is a typo and the name should be the same in both queries an inner (regular) join would work.
```
With ... | You can use `SUM(IF())`:
```
SELECT vwemployee.directorateName,
SUM(IF(vwemployee.directorateName = vwemployeeCourse.directorateName),1,0) directorateCount,
SUM(IF(vwemployee.Id = employeeCourse.employeeId),1,0) idCount,
FROM vwemployee , vwemployeeCourse
WHERE vwemployee.directorateName = vwemploye... | SQL QUERY- multiple COUNT returns wrong (same) results | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
sorry to disturb you but I got a problem with a count of union; I try to implement the same logic that I read in other post but it's not working for me, some help please?
This is my code:
/*Declaration of data*?
```
/*where i should make the count*/
/*first select*/
UNION
/*second select*/
/*in the where of the se... | Having a case statement in your where should not mess up the syntax. It is probably something else.
Make sure when doing a subquery you give it an alias.
```
SELECT COUNT(*)
FROM (
/*first select*/
UNION
/*second select*/
WHERE
CASE
WHEN ((@case='other')
AND (cfv.value LIKE '%,'... | If you're trying to get a count of all the records selected, you could do this:
```
SELECT COUNT(*) FROM
(
SELECT First...
UNION
SELECT Second...
) AS CountTable
```
Just wrap your whole query in another `SELECT` statement and count from there. | SQL query - Count of union of select | [
"",
"sql",
"sql-server",
"count",
"union",
""
] |
I have two tables
User Table:
```
UserID Username FirstName Lastname
1001 KiranReddy Kiran Reddy
1002 Arvind Arvind Kumar
1003 Arun Arrun Swamy
1004 Ramesh Ramesh Naidu
1005 Ramesh Ramesh Naidu
1006 Ajay1233 Ajay ... | ```
Select friend.UserID2 from User
left join Friend on friend.userid1 = user.userid
Where user.username like '%A' and friend.UserID1 ='1001'
``` | ```
SELECT u.Username
FROM Friend as f
INNER JOIN User as u
ON f.UserID2 = u.UserID
WHERE f.UserID1 = '1001'
AND u.Username LIKE "A%"
ORDER BY u.Username
```
That should do it. Of course you could return more than just the Username. | SQL Server : Subquery returned more than 1 value | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have 5 tables: A, B, C, D, E
A: {ID, Value, GroupID, FilterID, In\_Date}
B: {ID, Description, Out\_Date, From\_Date }
C: {ID, Category}
D: {GroupID, GroupName}
E: {FilterID, FilterName}
There could be missing IDs in B and C as a result, I'm trying to do a LEFT JOIN to get the required info. In my dataset, I've ... | 1) Don't mix old comma separated join syntax with modern explicit join syntax!
2) When `left join`, put the right side table's conditions in the `ON` clause to get true left join behavior. (When in `WHERE` you get inner join result.)
```
SELECT A.Value, A.Group, B.Description, C.Category, D.GroupName, E.FilterName
F... | Here is your table details
A: {ID, Value, GroupID, FilterID, In\_Date}
B: {ID, Description, Out\_Date, From\_Date }
C: {ID, Category}
D: {GroupID, GroupName}
E: {FilterID, FilterName}
now you try to retrieve data using left join
so you try the flowing script
```
SELECT A.Value, A.Group, B.Description, C.Ca... | What is wrong with the following SQL left join? | [
"",
"sql",
"join",
""
] |
```
SELECT CASE WHEN ISNUMERIC('1a') =1 THEN 1 ELSE 'A' END
```
i'am getting this error !!
> Conversion failed when converting the varchar value 'A' to data type int. | you are a victim of data type precedence.Taken from BOL:
> When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit c... | ```
SELECT CASE WHEN ISNUMERIC('1a') =1 THEN 1 ELSE 2 END
``` | Sql ISNUMERIC() | [
"",
"sql",
"sql-server",
""
] |
I have 2 tables. Table1 would be the main table.
Table2 contains data related to table1.
Table1:
```
WONUM
123
124
125
```
Table2:
```
wonum task holdstatus
123 1 APPR
123 2 APPR
123 3 APPR
124 1 COMP
124 2 APPR
125 1 COMP
... | You've almost got the right answer.
Try this query:
```
SELECT t1.wonum
FROM table1 t1
WHERE t1.wonum NOT IN (
SELECT t2.wonum
FROM table2 t2
WHERE t2.wonum = t1.wonum
AND t2.holdstatus = 'COMP'
);
```
This should give you all of the records you need. In this case, just record 123.
You can also do it using a... | You are close, you just need to use a `NOT EXISTS` and reverse your `holdstatus` condition:
```
Select *
From table1 t1
Where Not Exists
(
Select *
From table2 t2
Where t1.wonum = t2.wonum
And t2.holdstatus = 'COMP'
);
``` | Oracle SQL - Finding records from table1 where table2 condition does not exist | [
"",
"sql",
"oracle",
""
] |
Title sucks, I couldn't come up with a good one explaining what I want, sorry.
I have a complex query which I have simplified to one below. Basically it always must return one record. Main table has a left join (it can't be an inner join) with another table from which it retrieves count of records it matches and so fa... | I don't know why you need the type at the end, in the case if you can remove it, the query something like this
```
select a.id, a.type, count(asd.count) as count
from TableA a join
(select count(distinct b.id) as count, b.type
from TableB b
Group by b.type
) asd
on a.type = asd.type OR asd.... | should be this
```
select a.Type, count(*) from TableA a
left join
(select count(distinct b.id) count, b.type
from TableB b
Group by b.type) as asd
on a.type = asd.type or asd.type is null
where a.type = 'Email'
group by a.type
``` | GROUP BY - add result with null group by key to other result | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I am learning to use recursive query in db2, got a problem online to print following pattern
```
*
**
***
****
*****
******
*******
********
*********
**********
***********
```
upto 20 level, solved it in Oracle using following query
```
select lpad('*', level, '*') result from dual connect b... | Correct query for db2, using `REPEAT` instead of `LPAD`
```
with x(id,val) as
(
select 1, REPEAT('*',1) from sysibm.sysdummy1
union all
select id+1, REPEAT('*',id+1) from x where id < 20
)
select val from x
```
```
with x(id,val) as
(
select 20, REPEAT('*',20) from sysibm.sysdummy1
union all
select id-1, REPE... | Replace `dual` with `sysibm.sysdummy1`
```
select lpad('*', level, '*') result
from sysibm.sysdummy1
connect by level <= 20
``` | How to use Recursive query in db2 | [
"",
"sql",
"db2",
""
] |
I'm probably fundamentally misunderstanding temp tables -
But from within SSMS, I have the following:
```
Create Table #temp(FromUserId int, ToUserId int, FromAction int, ToAction int, IsMatch int)
```
If I Execute this twice, I get the error:
```
There is already an object named '#temp' in the database.
```
Why i... | Temp tables have scope either local to the connection or global to all connections. When I build procedures with temp tables I work in a normal query window and I have a drop statement before each create. Then when it is all set I add the create procedure code and comment out the drop table statements as during normal ... | Each SSMS tab is its own connection. Any temp objects you create won't get dropped until you close it or drop it explicitly. It's actually quite useful behavior. | Why can't I create a temp table twice in a row from SSMS? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a query (sql) to pull out a street name from a string. It's looking for the last occurrence of a digit, and then pulling the proceeding text as the street name. I keep getting the oracle
> "argument '0' is out of range"
error but I'm struggling to figure out how to fix it.
the part of the query in question is... | The fourth parameter of [`regexp_instr`](https://docs.oracle.com/cd/B12037_01/server.101/b10759/functions114.htm) is the occurrence:
> occurrence is a positive integer indicating which occurrence of
> pattern in source\_string Oracle should search for. The default is 1,
> meaning that Oracle searches for the first occ... | > looking for the last occurrence of a digit, and then pulling the proceeding text as the street name
You could simply do:
```
SELECT REGEXP_REPLACE( address, '^(.*)\d+\D*$', '\1' )
AS street_name
FROM address_table;
``` | Argument '0' is out of range error | [
"",
"sql",
"oracle",
"arguments",
""
] |
I have a table with 372 million rows, I want to delete old rows starting from the first ones without blocking the DB. How can I reach that?
The table have
```
id | memberid | type | timeStamp | message |
1 123 10 2014-03-26 13:17:02.000 text
```
UPDATE:
I deleted about 30 GB of Space ... | ```
select 1;
while(@@ROWCOUNT > 0)
begin
WAITFOR DELAY '00:00:10';
delete top(10) from tab where <your-condition>;
end
```
delete in chunks using above sql | You may want to consider another approach:
1. Create a table based on the existing one
2. Adjust the identity column in the empty table to start from the latest value from the old table (if there is any)
3. Swap the two tables using `sp_rename`
4. Copy the records in batches into the new table from the old table
5. Yo... | SQL - Delete table with 372 million rows starting from first row | [
"",
"sql",
"sql-server",
"large-data",
""
] |
these two query output different result,
I have question `AND m.status = $1 ...`each condition follow the left join table or move to the final part, thats different ??
query 1
```
SELECT count(mua.*)
AS total_row_count
FROM media_user_action mua
LEFT JOIN media m ON m.id = mua.media_id
AND m.status =... | When you use left outer join, value of the right table may be `NULL`.
For simplicity's sake, let say we have
`Table A (id, name)` and `Table B (fid, status)`
Then query1 will be like
```
select A.id, B.status
from A
left join (select * from B where status = $1)
on A.id = B.fid;
```
so result could have B.status i... | When you put `WHERE` conditions on tables that you have `LEFT JOIN`-ed, and that require some their fields to have non-NULL values, then you are actually converting the `LEFT JOIN` into an `INNER JOIN`.
This is because a `LEFT JOIN` may produce results where the joined table has no matching record. In that case all fi... | select left join table use and condition | [
"",
"sql",
"postgresql",
""
] |
We are doing some validation of data which has been migrated from one SQL Server to another SQL Server. One of the things that we are validating is that some numeric data has been transferred properly. The numeric data is stored as a float datatype in the new system.
We are aware that there are a number of issues with... | Your validation rule seems to be misguided.
An SQL Server `FLOAT`, or `FLOAT(53)`, is stored internally as a 64-bit floating-point number according to the IEEE 754 standard, with 53 bits of mantissa ("value") plus an exponent. Those 53 binary digits correspond to approximately 15 decimal digits.
Floating-point number... | You can try using `cast` to `varchar`.
```
select case when
len(
substring(cast(col as varchar(100))
,charindex('.',cast(col as varchar(100)))+1
,len(cast(col as varchar(100)))
)
) = 4
then 'true' else 'false' end
from tablename
where charindex('.',cast(col as varchar(100))) > 0
``` | How Can I Get An Exact Character Representation of a Float in SQL Server? | [
"",
"sql",
"sql-server",
"string",
"floating-point",
""
] |
I am working on building a new SSIS project from scratch. I want to work with couple of my teammates. I was hoping to get a suggestion on how we can have some have some source control, so that few of us can work concurrently on the same SSIS project (same dtsx file, building new packages.)
Version:
SQL Server Integrati... | It is my experience that there are two opportunities for any source control system and SSIS projects to get out of whack: adding new items to the project and concurrent changes to an existing package.
## Adding new items
An SSIS project has the .dtproj extension. Inside there, it's "just" XML defining what all belong... | A dtsx file is basically just an xml file. Compare it to a bunch of people trying to write the same book. The solution I suggest is to use Team Foundation Server as a source control. That way everyone can check in and out and merge packages. If you really dont have that option try to split your ETL process in logical p... | Source control in SSIS and Concurrent work on dtsx file | [
"",
"sql",
"sql-server",
"ssis",
"ssis-2012",
""
] |
## Explanation
I have a table which does not have a primary key (or not even a composite key).
The table is for storing the time slots (opening hours and food delivery available hours) of the food shops. Let's call the table "business\_hours" and the main fields are as below.
* shop\_id
* day (0 - 6, means Sunday - ... | It depends on several factors that you should specify:
1. How fast will the data grow
2. What is the estimated table size in rows
3. What queries will be run against that table
4. How fast do you expect the queries to run
It is more about thinking like: Some service will make thousands of inserts of new records per h... | Having decided against a primary key means the following would be allowed:
```
| shop_id | day | type | start_time | end_time
+---------+-----+--------+------------+---------
| 1000 | 1 | open | 09:00:00 | 13:00:00
| 1000 | 1 | open | 09:00:00 | 13:00:00
| 1000 | 1 | open | 17:00:00 | 22:0... | How to decide which fields must be indexed in a database table | [
"",
"mysql",
"sql",
"database",
"indexing",
""
] |
I have a Grades table where I have the following fields:
-STUDENT\_ID
-COURSE\_ID
-FIRST\_TERM
-SECOND\_TERM
-FINAL
And a Course table:
-COURSE\_ID
-NAME
-DEPARTMENT\_ID
I'm trying to get all the grades for a particular student with grades for each course specified, I was wondering how do I get th... | You can use this query:
```
SELECT s.student_id,
s.course_id,
c.course_name,
(s.first_term+s.second_term+s.final) AS "Total Mark"
FROM marks s
INNER JOIN course c ON c.course_id = s.course_id
WHERE s.student_id = 1
```
Make sure to prefix field names with table names w... | ```
SELECT student_id, m.course_id,c.name as course_name, (first_term+second_term+final) AS "Total Mark" FROM MARKS M inner join course c on m.course_id = c.course_id WHERE student_id = 1;
```
Use an inner join between marks and course table to get name from course table. | How to get each course name in a grades table where I only have the id for course? | [
"",
"sql",
""
] |
I have a table with records as below:
[](https://i.stack.imgur.com/GPG1D.png)
I need to verify that for each combination of Number, Name, if the Code is null then there is another record with same Number, Name which has Code as 1. There can be a reco... | If you are just trying to verify and make sure there are none (or find the ones which don't have a code = 1) then you can simply do this:
```
select number, name from table where code is NULL
minus
select number, name from table where code = 1
``` | ```
SELECT
T1.number,
T1.name
FROM
My_Table T1
WHERE
T1.code IS NULL AND
NOT EXISTS (
SELECT *
FROM My_Table T2
WHERE
T2.number = T1.number AND
T2.name = T1.name AND
T2.code = 1
)
``` | How can I check if each record of a database has a similar record for all columns except one? | [
"",
"sql",
""
] |
How to replace the value in 'projectId' column with project name assuming there is another table with name 'project' and two tables are related on the number mentioned after ':' in 'projectId' column of employee output.
```
> select * from employee;
+----+-----------+
| id | projectId |
+----+-----------+
| 1 | proje... | You need parenthesis around your subrequest.
```
update employee e
set projectId = concat('project:',
(select projectName
from projects
where projectId = substring_index(e.projectId, ':', -1)));
``` | This should do the job:
```
UPDATE employee e, projects p
SET e.projectId = CONCAT('project:',p.projectName)
WHERE substring_index(e.projectId,':', -1) = p.projectID
```
Is **project:** a constant or does it change? If so you need to take it over from employee | How to update mysql column with another value from another table? | [
"",
"mysql",
"sql",
""
] |
I have 2 column ID and description.I want to get the only mailid for each ID column.
```
ID Description
1 I have 2 mailID please note this mai1: anto1@gmail.com and mai1: anto2@gmail.com and mai1: anto3@gmail.com abbaaabbbbbbb.
2 I have 2 mailID please note this mai1: sample1@gmail.com and mai1: sample2@gmail.com... | Maybe something like this...
## Test Data
```
Declare @table TABLE(ID int , Description Varchar(8000))
INsert into @table values
(1 , 'I have 2 mailID please note this mai1: anto1@gmail.com and mai1: anto2@gmail.com and mai1: anto3@gmail.com abbaaabbbbbbb'),
(2 , 'I have 2 mailID please note this mai1: sample1@gmai... | ```
DECLARE @xml xml
--- Remove from here...
;WITH cte AS (
SELECT *
FROM (VALUES
(1, 'I have 2 mailID please note this mai1: anto1@gmail.com and mai1: anto2@gmail.com and mai1: anto3@gmail.com abbaaabbbbbbb.'),
(2, 'I have 2 mailID please note this mai1: sample1@gmail.com and mai1: sample2@gmail.com and mai1: samp... | How to find the string in large description value | [
"",
"sql",
"sql-server",
""
] |
I wrote a new query which gets me a listAgg result such as the below
```
Col A
1000016932,1000020056,1000020100,1000020144,1000020243
```
Now what i want with that results is as follows
`col C col D
1000016932 1000020056
1000016932 1000020100
1000016932 1000020144
1000016932 1000020243
1000020056 100... | ```
with table_1 (colA) as (
select '1000016932,1000020056,1000020100,1000020144,1000020243' from dual
),
prep (lvl, token) as (
select level, regexp_substr(colA, '[^,]+', 1, level) from table_1
connect by level <= regexp_count(colA, ',') + 1
and colA = prior colA
and p... | If I understand this correctly, you need to get all combinations of pair of values inside a comma separated string where order is not significant, excluding the same value pairs like (1,1), (2,2), etc.
The first step is to convert the string into rows and select a rownumber along with the values -
```
SELECT ROWN... | SQL query to listAgg and group by | [
"",
"sql",
"oracle",
"listagg",
""
] |
Each item(item is produced by Serial) in my table has many record and I need to get last record of each item so I run below code:
```
SELECT ID,Calendar,Serial,MAX(ID)
FROM store
GROUP BY Serial DESC
```
it means it must show a record for each item which in that record all data of columns be for last record related... | If you want the row with the max value, then you need a join or some other mechanism.
Here is a simple way using a correlated subquery:
```
select s.*
from store s
where s.id = (
select max(s2.id)
from store s2
where s2.serial = s.serial
);
```
You query uses a (mis)feature of SQL Server that generates lo... | try this one.
```
SELECT MAX(id), tbl.*
FROM store tbl
GROUP BY Serial
``` | List Last record of each item in mysql | [
"",
"mysql",
"sql",
"sorting",
""
] |
In our SSDT project we have a script that is huge and contains a lot of INSERT statements for importing data from an old system. Using sqlcmd variables, I'd like to be able to conditionally include the file into the post deployment script.
We're currently using the `:r` syntax which includes the script inline:
```
IF... | I ended up using a mixture of our build tool (Jenkins) and SSDT to accomplish this. This is what I did:
1. Added a build step to each environment-specific Jenkins job that writes to a text file. I either write a SQLCMD command that includes the import file or else I leave it blank depending on the build parameters the... | Rather than muddy up my prior answer with another. There is a special case with a VERY simple option.
Create separate SQLCMD input files for each execution possibility.
The key here is to name the execution input files using the value of your control variable.
So, for example, your publish script defines variable 'Co... | How can I conditionally include large scripts in my ssdt post deployment script? | [
"",
"sql",
"sql-server",
"sql-server-2014",
"sql-server-data-tools",
""
] |
I have this select:
```
SELECT
*,
(SELECT some_value FROM other_table) as a1,
(SELECT some_value FROM other_table2) as a2
FROM some_table;
```
Is there any way to use the values a1, a2 and work with them like this?
```
SELECT
*,
(SELECT some_value FROM other_table) as a1,
(SELECT some_value FROM other_table2) ... | Use `WITH` in Oracle. It's very helpful. [Link](https://oracle-base.com/articles/misc/with-clause)
```
WITH a1 AS (SELECT some_value FROM other_table),
a2 AS (SELECT some_value FROM other_table2)
SELECT *
FROM some_table t
JOIN a1 ON a1.key = t.key
JOIN a2 ON a2.key = t.key
``` | Try
```
SELECT t.*,
a1.some_value + a2.some_value,
a1.some_value / a2.some_value
FROM some_table t
cross join (SELECT some_value FROM other_table) as a1
cross join (SELECT some_value FROM other_table2) as a2
``` | sql working with alias from other select | [
"",
"sql",
"oracle11g",
""
] |
I have quick question why I can't use having keyword on distance? I need somehow to check is distance < 20 for example
```
SELECT
Id, Lat, Lng,
(6367 * acos( cos( radians(45.444) )
* cos( radians( Lat ) ) * cos( radians( Lng ) - radians(158.554) )
+ sin( radians(4545) ) * sin( radians( Lat ) ) ) )... | Try this
```
SELECT *
FROM
(SELECT
Id, Lat, Lng,
(6367 * acos(cos(radians(45.444)) * cos(radians(Lat)) *
cos(radians(Lng) - radians(158.554)) + sin(radians(4545)) *
sin(radians(Lat)))) AS distance
FROM Posts) p
WHERE
p.distance < 15
ORDER BY
p.distance
``... | I might suggest `outer apply` for this purpose:
```
SELECT p.Id, p.Lat, p.Lng, d.distance
FROM Posts p OUTER APPLY
(SELECT (6367 * acos( cos( radians(45.444) )
* cos( radians( p.Lat ) ) * cos( radians( p.Lng ) - radians(158.554) )
+ sin( radians(4545) ) * sin( radians( p.Lat ) ) ) ) AS d... | Invalid column name on Having in SQL Server | [
"",
"sql",
".net",
"sql-server",
""
] |
I have two queries below, which to me are the same so should return the same results. However they do not, the bottom query is not returning any data but I can't see why?
query below return the correct data
```
SELECT myDate, myTicker, SUM(myUnits) AS mUnits
FROM myTbl
where myName = 'abc4' and myDate... | Set size for `NVARCHAR(4)`
```
DECLARE @myF NVARCHAR(4), @FromDate DATE
SET @myF = 'abc4'
``` | the main reason is `Default Length` for `NVARCHAR` is `1`
So,your this query
```
declare @myF nvarchar, @FromDate date
set @myF = 'abc4'
set @FromDate = '2016-04-13'
SELECT myDate, myTicker, SUM(myUnits) AS mUnits
FROM myTbl
where myName = @myF and myDate >= @FromDate
GROUP BY myDate, myTicker
```
Re... | two queries returning different data | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Suppose that we have two tables:
TABLE TA
```
AID BID1 BID2
-- ---- ----
01 01 02
02 01 03
03 02 01
```
TABLE TB
```
BID Name
--- ----
01 FOO
02 BOO
03 LOO
```
If I want to return the following:
```
AID Name1
-- -----
01 FOO
02 FOO
03 BOO
```
I write the following:
```
SELECT TA.AID, TB.Name as... | You could join multiple times:
```
SELECT TA.AID, tb1.Name AS Name1, tb2.Name AS Name2
FROM TA
LEFT JOIN TB tb1
ON TA.BID1 = tb1.BID
LEFT JOIN TB tb2
ON TA.BID2 = tb2.BID;
```
Note: `LEFT OUTER JOIN` will ensure you always get all records from `TA` even if there is no match.
`LiveDemo` | Just use one more join
```
SELECT TA.AID, TB.Name as Name1, T1.Name as Name2
FROM TB
INNER JOIN TA on TB.BID=TA.BID1
INNER JOIN TB T1 on T1.BID=TA.BID2;
``` | INNER JOIN for two columns of the same foreign key | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
The simplified version is this: I have a table with two fields. The first field, `trx`, will always have a value. The second field, `tstop`, can be either null or a timestamp.
I would like to organize the output from the select such that the first "group" of records all have tstop of null, the remaining records have a... | You could use `IS NULL`:
```
SELECT *
FROM rx
ORDER BY tstop IS NULL DESC, trx DESC
```
`SqlFiddleDemo` | Just `order by` the columns and use the option `nulls first` to make `null` values appear first:
```
SELECT *
FROM rx
ORDER BY tstop DESC NULLS FIRST, trx DESC
``` | Grouping select output by null value in PostgreSQL | [
"",
"sql",
"database",
"postgresql",
"postgresql-9.5",
""
] |
I have read a lot of other posts here on stackoverflow and google but I could not find a solution.
It all started when I changed the model from a CharField to a ForeignKey.
The error I recieve is:
```
Operations to perform:
Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages
Apply a... | Looks like you added `null=True` after created migration file. Because `venue_city` is not a nullable field in your migration file
Follow these steps.
```
1) Drop venue_city & venue_country from your local table
3) Delete all the migration files you created for these `CharField to a ForeignKey` change
4) execute `pyt... | Had a similar problem i resolved it by removing the previous migration files.No technical explanation | django.db.utils.IntegrityError: column "venue_city" contains null values | [
"",
"sql",
"django",
"postgresql",
"django-models",
"django-migrations",
""
] |
I'm using this PostgreSQL table to store configuration variables:
```
CREATE TABLE SYS_PARAM(
SETTING_KEY TEXT NOT NULL,
VALUE_TYPE TEXT,
VALUE TEXT
)
;
```
[](https://i.stack.imgur.com/Dxq2M.png)
How I can update all configuration settings value... | If you plan on performing these updates more than once or twice over time, it would be good to have a function handle this for you. You could use the table itself as a type for a variadic parameter within a function, like so:
```
-- The function
CREATE OR REPLACE FUNCTION update_sys_param(VARIADIC params sys_param[])
... | you can use `where true` at the end and it update all rows in your table.
for example:
```
UPDATE table_name set table_column = value where true;
```
it will be update all rows in one SQL query. | Update all rows with one SQL query | [
"",
"sql",
"postgresql",
"sql-update",
"postgresql-9.1",
"postgresql-9.3",
""
] |
i'm trying to write a query which prevents inserting duplicated rows as below
```
INSERT INTO RSS_SETTING_ADMIN (ID_PRODUCT , ID_RSS , ID_CATEGORY , ID_TYPE_USER)
VALUES (384 , 3, 283 , 1)WHERE NOT EXISTS
(SELECT * FROM RSS_SETTING_ADMIN
WHERE ID_PRODUCT = 384 , ID_RSS = 3 , ID_CATEGORY = 283, ID_TYPE_USER = 1)
```
... | Your command should be:
```
INSERT INTO RSS_SETTING_ADMIN (ID_PRODUCT , ID_RSS , ID_CATEGORY , ID_TYPE_USER)
SELECT 384 , 3, 283 , 1 FROM DUAL
WHERE NOT EXISTS
(SELECT * FROM RSS_SETTING_ADMIN
WHERE ID_PRODUCT = 384
AND ID_RSS = 3
AND ID_CATEGORY = 283
AND ID_TYPE_USER = 1
);
```
I al... | If you want to prevent the insertion of duplicate values, then you should use a unique constraint/index on the table:
```
alter table RSS_SETTING_ADMIN
add constraint unq_RSS_SETTING_ADMIN_4 unique(id_product, id_rss, id_category, id_type_user);
```
It is a much better approach to let the database maintain relati... | writing oracle insert query which prevents from inserting duplicated rows | [
"",
"sql",
"oracle",
""
] |
I am trying to write a SQL query to extract records from a single table that have the same `model_number` field, but different `primary_use` fields. I have been able to query for duplicates, but my query makes no distinction if a record is truly a duplicate or if `primary_use` is different. I'm not interested in where ... | With SQLite I believe your best bet is a self join:
```
SELECT DISTINCT t1.*, t2.*
FROM yourtable as t1
INNER JOIN yourtable as t2 ON
t1.model_number = t2.model_number AND
t1.primary_use <> t2.primary_use;
```
Joining the table to itself where model\_number is the same, but primary\_use is differe... | Some examples would help, but it sounds like
```
select distinct model_number, primary_use from [table]
```
or perhaps
```
select model_number, primary_use from [table]
group by model_number, primary_use
``` | Query for records that are the same in one field, but different in another? | [
"",
"sql",
"sqlite",
""
] |
I am using mysql.
I have a table that has a column id.
Let us say I have an input set of ids. I want to know which all ids are missing in the table.
If the set is "ida", "idb", "idc" and the table only contains "idb", then the returned value should be "ida", "idc".
Is this possible with a single sql query? If not, ... | MySQL will only return rows that exist. To return missing rows you must have two tables.
The first table can be temporary (session/connection specific) so that multiple instances can run simultaneously.
```
create temporary table tmpMustExist (text id);
insert into tmpMustExist select "ida";
insert into tmpMustExist ... | ```
//you can pass each set string to query
//pro-grammatically you can put quoted string
//columns must be utf8 collation
select * from
(SELECT 'ida' as col
union
SELECT 'idb' as col
union
SELECT 'idc' as col ) as setresult where col not in (SELECT value FROM `tbl`)
``` | Find values missing in a column from a set (mysql) | [
"",
"mysql",
"sql",
""
] |
I have following **[RestaurantOffer]** table.
Offers, which is valid only within two date ranges (i.e FromDate and ToDate) and at a particular timing(FromTime,ToTime).
[](https://i.stack.imgur.com/sqzQt.png)
So I want to write a query which would giv... | Try this:
```
--DROP TABLE #temp
CREATE TABLE #temp
(
FROMDate DATE
, ToDate DATE
, FromTime TIME
, ToTime TIME
);
INSERT INTO #temp
( FROMDate, ToDate, FromTime, ToTime )
VALUES ( '2016-05-01' -- FROMDate - date
, '2016-06-01' -- ToDate - date
, '11:30:00:00... | Try following query:
```
SELECT * FROM RestaurantOffer WHERE (GETDATE() >= FromDate AND GETDATE() <= ToDate) AND (cast(GETDATE() as datetime) >= FromTime AND cast(GETDATE() as datetime) <= ToTime);
``` | Get database records which satisfy two date ranges and within a specific timing in SQL server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
"sql-server-2012",
""
] |
In my database I am renaming a table. I tried to rename it by using
```
exec sp_rename Student,Students
```
but I got the message:
> Caution: Changing any part of an object name could break scripts and stored procedures.
How can I avoid getting this message? | Unfortunately, this message cannot be suppressed.\*
There was a [Microsoft Connect ticket](https://connect.microsoft.com/SQLServer/feedback/details/266048/sp-rename-suppress-caution-warning-message) submitted by our very own [Aaron Bertrand](https://stackoverflow.com/users/61305/aaron-bertrand), but it was closed as w... | The way to do it is this:
Extract the source code of sp\_rename from your Master database.
Make a copy of it somewhere else under a different name e.g. "quiet\_rename"
Remove / comment out this line from the code:
```
raiserror(15477,-1,-1)
```
now you have your own local copy of sp\_rename without the annoying erro... | How to hide Caution: Changing any part of an object name could break scripts and stored procedures | [
"",
"sql",
"sql-server",
""
] |
The below query gives a set of rows with 3 columns.
```
Select
c.CaseID, i.ImageID, i.ImagePath
From
tblCase c WITH (NOLOCK)
inner join
tblName n WITH (NOLOCK) on c.CaseID = n.CaseID
inner join
tblImage i WITH (NOLOCK) on n.NameID = i.NameID
where
n.NameCode = '70'
```
The ImagePath column ... | The best idea would be to stop storing multiple values in one column and normalize the database so that you don't run into issues like this.
Barring that, you can try to use `REPLACE()`, but you need to be very careful that you don't inadvertently change parts of the string that happen to match with your string.
```
... | Here is a try:
```
declare @s varchar(max) = 'ImageID=3215;FilePath=\2016\5\13\test.tif;ImageType=original;PageNumber=1'
select substring(@s, 0, charindex('imagetype=', @s)) + 'ImageType=duplicate' +
substring(@s, charindex(';', @s, charindex('imagetype=',@s)), len(@s))
```
<http://rextester.com/edit/AVQO5889... | How to update a column for a set of rows? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
Using MSSQL
I have a table of users, and a table of products to which they are subscribed. Those subscriptions are either Free (F) or Paid (P). I have joined the tables, converted the F/P value to numeric using a case statement, and then summed up those values by user ID, the idea being that anyone with only free acco... | Re-using the query from the question you can create a CTE (or a subquery) and aggregate the results:
```
;WITH CTE_UserAccounts AS (
SELECT t1.user_id, SUM(
CASE
WHEN t2.free_paid = 'P'
THEN 1
ELSE 0
END ) as highest
FROM users t1 INNER JOIN accounts t2
... | ```
SELECT
COUNT(DISTINCT CASE WHEN t2.free_paid = 'P' THEN t1.user_id END) as atleast_one_paid,
COUNT(DISTINCT CASE WHEN t2.free_paid <> 'P' THEN t1.user_id END) as onlyfree
FROM users t1
INNER JOIN accounts t2 ON t1.user_id = t2.user_id
WHERE t2.account = 'A'
``` | Aggregating SQL results, two tables, then summarizing results | [
"",
"sql",
"sql-server",
""
] |
i am running this SQL query:
```
SELECT a.retail, b.cost
from call_costs a, call_costs_custom b
WHERE a.sequence = b.parent
AND a.sequence = '15684'
AND b.customer_seq = '124'
```
which returns both `a.retail` and `b.cost` if the row exists in `call_costs_custom` but if the row does not exist, i want to show ju... | You want an outer join, i.e. a join that keeps records from the first table even when there is no match in the second table. Use `LEFT OUTER JOIN` or short `LEFT JOIN` hence:
```
select cc.retail, ccc.cost
from call_costs cc
left join call_costs_custom ccc on ccc.parent = cc.sequence and ccc.customer_seq = '124'
wher... | From W3Schools:
> The LEFT JOIN keyword returns all rows from the left table (table1),
> with the matching rows in the right table (table2). The result is NULL
> in the right side when there is no match.
```
SELECT
a.retail,
b.cost
FROM
call_costs a
LEFT JOIN
call_costs_custom b
ON
a... | sql query selecting from two tables - return results from one table if there are none in the other table | [
"",
"mysql",
"sql",
""
] |
Here are my tables:
```
CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL,
`post_limit` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `category` (`id`, `title`, `post_limit`) VALUES
(1, 'News',... | I think you need to enumerate the articles to apply the `post_limit`. You can do this with a subquery:
```
select a.*
from (select a.*,
(@rn := if(@c = a.category_id, @rn + 1,
if(@c := a.category_id, 1, 1)
)
) as rn
from articles a cross jo... | To limit the count of each category to the category's `post_limit`:
```
select c.id, c.title, least(post_limit, count(a.id))
from category c
left join article a on category_id = c.id
group by 1, 2 -- or "group by c.id, c.title" if you prefer the verbose style
```
See [SQLFiddle](http://sqlfiddle.com/#!9/c4f739/2). | How do I select an exact number of articles for each category? | [
"",
"mysql",
"sql",
""
] |
I want to round value of one select
For example:
```
select width from Home
```
The result of `width` is "3.999999999999999"
I want to be "3.99" or "3.9" | If you need only two decimal values you can multiply by 100, floor the result and divide by 100 (This is necessary because floor works only flooring a number to an integer):
```
select floor(width * 100) / 100 from Home
```
Here are the steps
```
3.99999999 * 100 = 399.999999 --- Multiply by 100
floor(399.999999)... | `ROUND(width, 1 or 2, 1)` should work best for you. Example:
```
SELECT CONVERT(NUMERIC(13,2), ROUND(width, 2, 1))
FROM Home
```
will return 3.99, and
```
SELECT CONVERT(NUMERIC(13,1), ROUND(width, 1, 1))
FROM Home
```
will return 3.9 | SQL Server round() | [
"",
"sql",
"sql-server",
"rounding",
""
] |
```
SELECT
table_comments1.*, table_comments2.*
FROM
[table_comments1], [table_comments2]
INNER JOIN
[users] ON [table_comments1].fk_user_id = [users].user_id
AND [table_comments2].fk_user_id = [users].user_id
ORDER BY
comment_date DESC
```
What am I doing wrong? I'm getting this err... | try this
```
select t1.*, t2.*
from [table_comments1] t1 inner join users u
on t1.fk_user_id = u.user_id
inner join [table_comments2] t2
on t2.fk_user_id = u.user_id
``` | FYI There are several types of `join`
`t1 inner join t2 on t1.id = t2.fkId` (this is default if `inner` or anything else is ommited) returns records from t1 and t2 where exist matching records in t1 and t2. Old style (`ANSI 89`) looks like this: `...from t1,t2 where t1.id = t2.fkId`
`t1 left join t2 on t1.id = t2.f... | Error when selecting from two tables and performing an inner join on another | [
"",
"sql",
"sql-server",
""
] |
So I am trying to run a query but I'm having some problems with it because I'm using a `nvarchar` column to get a percentage column which gives me the percentage from the database of different data that I have. That column is called "Filetype" and what I have there is all the Extension's that I put there f.e: .exe, .zi... | You can do something like this.
```
with cte as
(
SELECT
Filetype AS [Extensão],
COUNT(*) AS [Nº de ficheiros],
CAST(((COUNT(Filetype) * 100.0) / (SELECT COUNT(*) FROM infofile)) AS DECIMAL(10,2)) AS [Percentagem (%)],
SUM(Filesize) AS [Total(KB)],
NULL AS [Convertido para MB],
MIN(COUNT(*)) OVER () * 100.0 / (SUM(C... | Probably no need for min/max percentage at first part, just at the second. As far as I've got it from comments, look at
```
WITH totals_by_ext AS (
SELECT
Filetype AS [Extensão],
COUNT(*) AS [Nº de ficheiros],
CAST(((COUNT(Filetype) * 100.0) / (SELECT COUNT(*) FROM infofile)) AS DECIMAL(10,2)) AS [Perc... | Query to run max and min | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
What is the most efficient way to get prime numbers from 2 to 1000 via SQL in MongoDB/MySQL/CockroachDB?
My query in Oracle:
```
WITH NUM AS (
SELECT LEVEL N
FROM DUAL CONNECT BY LEVEL <= 1000
)
SELECT LISTAGG(B.N,'-') WITHIN GROUP(ORDER BY B.N) AS PRIMES
FROM (
SELECT N,
CASE WHEN EXISTS ... | In PostgreSQL probably the most fastest query that prints prime numbers up to 1000 is:
```
SELECT regexp_split_to_table('2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269... | The most obvious improvement is that instead of checking from 1 to n you can check from 1 to the square root of n.
A second major optimization would be to use a temporary table to store the results and check them first. This way you can iterate incrementally from 1 to n, and only check the known primes from 1 to squar... | Best Logic to Print Prime Numbers with SQL query | [
"",
"sql",
"select",
"subquery",
""
] |
I want to convert seconds to `minute : seconds` format in sql select statement.
At the moment I am using:
```
SELECT SEC_TO_TIME(duration) from messages;
```
It works perfectly but it gives me this format of time: `hh:mm:ss`
but I need `mm:ss`
Is it possible to convert seconds into `mm:ss` format using sql query? | If the value is less than an hour, then just do:
```
SELECT RIGHT(SEC_TO_TIME(duration), 5) from messages;
```
If you might go over an hour, then do the arithmetic:
```
SELECT CONCAT_WS(':', FLOOR(SEC_TO_TIME(duration) / 60),
SEC_TO_TIME(duration) % 60)
``` | I recently had a similar project where I needed to convert stored seconds to `m:ss` format. No matter the amount, there needed to be at least one digit representing minutes and two digits representing seconds. The hours placeholder was forbidden, so the minutes value could acceptably go beyond `59` and also contain mor... | MySQL: How to convert seconds to mm:ss format? | [
"",
"mysql",
"sql",
"format",
""
] |
I've scoured the forums, but couldn't quite find a proper solution.
I have two tables with the following information:
-TableA-
```
Id | Created
11111 | 2016-01-01
22222 | 2016-02-02
33333 | 2016-03-03
```
-TableB-
```
Id | Created | Comment
11111 | 2016-01-01 | Blah Blah Blah
11111 ... | To get your expected result, you should use this:
```
SELECT C1.Id,
C1.Created,
MIN(C2.Created) AS Created2,
DATEDIFF(C1.Created, MIN(C2.Created)) AS DaysDiff
FROM (select id, min(created) created from TableB group by id) C1
JOIN TableB C2
ON C1.Id = C2.Id
AND C2.Created > C1.Created
G... | Try something like this:
```
select A.id, A.created, B.created, DATEDIFF(B.created, A.created) AS DaysDiff
from TableA A
join TableB B on B.id = A.id and
B.created = (select min(created) from TableB where
created > A.created)
```
Here's a SQLFiddle to try it: <http://www.sqlfiddle.com/#!9/859113/3> | SQL - Getting date difference between two rows between three tables | [
"",
"sql",
""
] |
Is it possible to check the time between ,let's say 19:00 to 08:00 of next day using `BETWEEN` ? I'm only using `time`.(not `datetime`) | Sure:
WHERE NOT time BETWEEN '8:00' AND '19:00' | ```
select *
from MyTable
where CAST(mytime as time) >= '19:00:00'
and CAST(mytime as time) < '08:00:00'
``` | BETWEEN IN SQL to check a time between two times | [
"",
"sql",
"sql-server",
"between",
""
] |
Provided the following structure and data:
```
CREATE TABLE "CHANGES" (
"ID" NUMBER(38),
"LAST_UPD_DATE" DATE DEFAULT SYSDATE
);
CREATE TABLE "EXPORT_LOG" (
"ID" NUMBER(38),
"LAST_EXPORT" DATE DEFAULT SYSDATE
);
```
Table `CHANGES` contains:
```
----------------------------
| ID | LAST_UPD_DATE |
... | Try this:
```
SELECT t1.*
FROM CHANGES AS t1
LEFT JOIN EXPORT_LOG AS t2 ON t1.ID = t2.ID
WHERE (t2.ID IS NULL) OR (t1.LAST_UPD_DATE > t2.LAST_EXPORT)
```
This will return all records of `CHANGES` table that don't have a match in `EXPORT_LOG` table **plus** the records of `CHANGES` table that have a `LAST_UPD_DATE` t... | One method is to translate the conditions directly using `exists`:
```
select c.*
from changes c
where not exists (select 1 from export_log el where c.id = el.id) or
not exists (select 1 from export_log el where c.id = el.id and el.last_export > c.last_upd_date);
```
This can be simplified to:
```
select c.*
f... | SQL: Join/union of two tables, on multiple conditions | [
"",
"sql",
"oracle",
"join",
""
] |
For some reason, these two SQL statements not equivalent. Can anybody help in understanding why?
```
SELECT N, IF(P IS NULL, 'Root', IF(N NOT IN (SELECT P FROM BST), 'Leaf', 'Inner'))
FROM BST
ORDER BY N;
SELECT N, IF(P IS NULL, 'Root', IF(N IN (SELECT P FROM BST), 'Inner', 'Leaf'))
FROM BST
ORDER BY N;
```
P.S. - T... | jarlh's comment above is correct, i.e. nothing compares TRUE with NULL except the test IFNULL or 'is null'. So if the query:
```
(SELECT P FROM BST)
```
returns a single NULL value, the two SQL statements will return different results. This can easily be demonstrated with the following two SQL statements:
```
select... | Nope. `NOT IN` has strange semantics when the underlying table has `NULL` values. In this case, the clause filters out all rows.
For this reason, I think `NOT EXISTS` is a better alternative:
```
NOT EXISTS (SELECT 1 FROM BST WHERE BST.P = BST.N)
```
You can also fix this by adding `WHERE P IS NOT NULL` to the two s... | Use of IN / NOT IN in mySQL | [
"",
"mysql",
"sql",
""
] |
i am not sure which is the best for color store in sql
i can be perform 3 way Color Name ,Hex color code , RGB Color Code. what is the datatype for the color .
please suggest me i am working a eCommerce side with Asp.net MVC and sql 2012. i need to store product color .
[ as CustomerCount,
(select count(*) from extractsummary) as Total,
rou... | This is a type problem. The expression
```
count(*)
```
results in type `bigint`. The expression
```
(select count(*) from extractsummary)
```
also results in type `bigint`. Unlike some programming languages (e.g. R), the division operator in PostgreSQL does not automatically promote integer operands to a fractiona... | I'm not sure what problems you are having, but analytic functions are a simpler method than subqueries:
```
select retpre04recency,
count(*) as CustomerCount,
sum(count(*)) over () as Total,
round(count(*)/sum(count(*)) over (), 2) as CustomerCount
from extractsummary
group by retpre04recency
ord... | What is the best way to use Total to get percentage of groups in PostgreSQL | [
"",
"sql",
"postgresql",
""
] |
I need to count the percentage of finalized transactions compared to total transactions (e.g. including in-process and finalized transactions). From looking around the web, I arrived at:
```
SELECT 100 * (SELECT COUNT(transaction_id) from t_transaction_main
WHERE due_date = '2016-05-16' and (suspend_status !='' OR
... | Wrong clause sequence you put the where before the from clause
```
SELECT 100 * (SELECT COUNT(transaction_id)
from t_transaction_main
WHERE due_date = '2016-05-16' and (suspend_status !='' OR
close_date !='0-0000-00'))/COUNT(transaction_id)
FROM t_transaction_main as test
WHERE due_date = '2016... | Why would you use a subquery? Or even two aggregation functions?
```
SELECT AVG(CASE WHEN suspend_status <> '' OR close_date <> '0-0000-00'
THEN 100.0 ELSE 0
END)
FROM t_transaction_main test
WHERE due_date = '2016-05-16' ;
```
This is *much* simpler than your original query. | Calculating percentage from two SQL Count() results | [
"",
"sql",
"count",
"percentage",
""
] |
this is my first stackoverflow question so please be gentle ;-)
I have a table with unique customerIDs and a table including their transactions with a certain transaction type (purchase, presell etc.)
What I want to count is all customers that have done a specific transaction type once. But if a customer has made an ... | When you look at it, it is the first presell per customer you are interested in. You can get that easily by selecting `MIN(TransactionDate)` per customer. Once you've done this, you can count.
```
select year, count(*)
from
(
select customerid, min(transactiondate) as year
from transactions
where transactiontype... | Since you want to count `Customers` by `TransactionType`, you should be grouping by `CustomerID` and `TransactionType`, not the `TransactionDate`:
```
SELECT datepart(yyyy,t.TransactionDate) -- this part won't work anymore without grouping it. Doesn't seem to be relevant to what you're selecting
,count(DISTINCT c... | Count distinct with repeating entries over time | [
"",
"sql",
"t-sql",
"sql-server-2012",
""
] |
I have want to retrieve the string after. From a table pos which has values like:
```
Office.Secretary
XYZ.Manager - Liaison
ABC.Community Relations Officer
```
This should be converted to
```
Secretary
Manager - Liaison
Community Relations Officer
```
I am using this :
```
SELECT REGEXP_REPLACE(REGEXP_SUBSTR (na... | ```
select regexp_replace('ABC.Community Relations Officer','([^\.]{0,}\.)(.*)','\2') from dual;
```
Try regexp group capturing.
`1-st group ([^\.]{0,}\.)` - match everything to first dot with dot.
`2-nd group (.*)` - match everything after dot.
`'\2'` - replace whole string with value from 2nd group.
With this... | If you need to remove a chunk of string from the beginning and up to the *first* dot, you need to use a negated character class regex solution:
```
SELECT REGEXP_REPLACE(name, '^[^.]+[.]', '') FROM table_POS;
```
Note that here,
* `^` - matches the start of a string
* `[^.]+` - matches 1 or more characters other tha... | To get the string after . through regex in oracle | [
"",
"sql",
"regex",
"oracle",
""
] |
I have a table of about 50k records. It looks something like this:
```
Animal | Name | Color | Legs
Cat |George| Black | 4
Cat | Bob | Brown | 4
Cat | Dil | Brown | 4
Bird | Irv | Green | 2
Bird | Van | Red | 2
```
etc.
I want to only insert Cat once and Bird only once and so on. The Name / Color ... | you can use group by only on animal name and select the rest of the column from Max() to get the first finding.
```
insert into MyNewTable
Select MAT.Animal,max(MAT.Name),max(MAT.Color),max(MAT.Legs)
From MyAnimalTable MAT GROUP BY MAT.Animal
``` | Use `ROW_NUMBER` to number the rows per animal and only keep the ones numbered 1.
```
insert into mynewtable (animal, name, color, legs)
select animal, name, color, legs
from
(
select
animal, name, color, legs,
row_number() over (partition by animal order by animal) as rn
from myanimaltable a
) numbered
w... | How can I insert values as a distinct column? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I want to have a select that will not have fixed number of columns.
Column `OptionalColumn` should be selected only if variable *@check* = 1
This is what I had (syntax is bad but maybe it explains my problem)
```
SELECT
Column1, Column2,
(IF @Check = 1
BEGIN OptionalColumn END)
FROM table
```
It is c... | You could do this with an IF ELSE block like this;
```
CREATE TABLE #table (Column1 varchar(10), Column2 varchar(10))
INSERT INTO #table
VALUES
('column1', 'column2')
DECLARE @Check bit; SET @Check = 0
IF @Check = 1
(SELECT Column1, Column2
FROM #table)
ELSE
(SELECT Column1
FROM #table)
```
Change the variable f... | Rich Benner gave you a good solution, as an alternative you can use dynamic sql like that :
```
DECLARE @sqlvar VARCHAR(100)
select @Sqlvar= ' SELECT Column1, Column2 '+IIF (@check=1,',OptionalColumn','')+' from TABLE';
EXECUTE sp_executesql @sqlvar
```
For reference on sp\_ executesql look:
[https://msdn.microsoft.... | Select certain column only if condition met | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
This question is already answered multiple times but I just can't get it to works. I tied use some answer from [this](https://stackoverflow.com/questions/16423883/how-to-retrieve-same-column-twice-with-different-conditions-in-same-table) question but I always "get error more than one row returned by a subquery used as ... | You could add another join to the `player_match_activity` table, or you could change `pma.activity_id = '1'` to `pma.activity_id IN ('1','2')` and use `CASE` expressions to choose the populate the proper columns:
```
SELECT DISTINCT p.name, pma_goal.time AS goal, pma_assist.time AS assist
FROM player p
INNER JOIN pl... | The way this query is created, the easiest way to do it is to join the player\_match\_activity table twice:
```
SELECT DISTINCT p.name, pma_goal.time AS goal, pma_assist.time AS assist
FROM player p JOIN player_match pm ON p.player_id = pm.player_id
JOIN matches m ON m.match_id = pm.match_id
JOIN team_match tm ON tm.t... | Retrieve same column twice with different conditions | [
"",
"sql",
"database",
"postgresql",
""
] |
I have a query that is joined to 3 tables. Without "DISTINCT" the total records is 331 but with Distinct the total number is 113. I want to get the 113 total only which is the total of distinct records. I used Count but it gives me the total number of not unique records. Please help me get the total of distinct records... | You can use the distinct in a sub query:
```
SELECT *
, COUNT(*) over() as totalRows
FROM (
SELECT DISTINCT
uf.OrigFileName,
uf.CreatedOn,
sdiTran.Status,
sdiFS.FileName,
sdiFile.ArchiveLogID
FROM [SDI].dbo.UploadedFile uf
inner join [SDI].dbo.SDIFile sdiFile on uf.UploadedFullFile... | If you want 331 rows with the count of 113 in each row, you can use a trick. Use `row_number()` to enumerate the rows with the same values and then use a window function to count when the number is 1:
```
SELECT t.*,
SUM(CASE WHEN seqnum = 1 THEN 1 ELSE 0 END) OVER () as CountDistinct
FROM (SELECT uf.OrigFileNa... | Get Total Number of Records after Distinct SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2014",
""
] |
I have a table which does not have any auto increments. I have to insert data into this table, each time incrementing the ID by 1000.
So I have
```
SELECT @maxId = Max(ID)
INSERT INTO TABLE1
(ID, DATA)
VALUES
(@maxId + 1000, DATA),
(@maxId + 2000, DATA),
(@maxId + 3000, DATA)
```
Instead of explici... | There is nothing stopping you from doing the following and getting the data inserted correctly.
```
insert into table1(ID,DATA)
VALUES ((select max(id) from table1 as T) +1000, DATA),
((select max(id) from table1 as T) +1000, DATA);
```
Or is it something else that you meant? | You can declare the field this way:
```
MyID INT IDENTITY (0,1000);
```
This will auto increment each record by 1000.
For example:
```
CREATE TABLE MyTable
(
MyID INT IDENTITY(0,1000),
SField VARCHAR(128)
);
INSERT INTO MyTable (SField) VALUES ('TEST');
INSERT INTO MyTable (SField) VALUES ('TEST1');
INSER... | Increment Variable in SQL | [
"",
"sql",
"sql-server",
""
] |
Why the result of this two nvarchar to DateTime is different?
```
Declare @ApplyDate nvarchar(max)
Set @ApplyDate = N'2014-01-01'
Print CONVERT(datetime, @ApplyDate , 120)
Exec(' print CONVERT(datetime, ' + @ApplyDate + ', 120) ')
```
result is:
```
Jan 1 2014 12:00AM
Jul 6 1905 12:00AM
``` | In this query:
```
Exec(' print CONVERT(datetime, ' + @ApplyDate + ', 120) ')
```
you are inserting `@ApplyDate` without quotes, which effectively turns into:
```
print CONVERT(datetime, 2014-01-01, 120)
```
which is of course equivalent to:
```
print CONVERT(datetime, 2012, 120)
```
where 2012 is read as... | You have missed extra single quotes around string value in your second example, so it doesn't get recognized as string.
It should be
```
Exec(' print CONVERT(datetime, ''' + @ApplyDate + ''', 120) ')
```
In this case both examples outputs same date. | Convert nvarchar to DateTime returns back different dates | [
"",
"sql",
"sql-server",
"datetime",
"type-conversion",
""
] |
I'm trying to Left Join Multiple tables with two sum columns that both join on a mid step table.
The tables look like:
**Table1**
```
ID Value1
1 3
2 2
3 3
```
**Table2**
```
ID Value1
1 5
2 2
3 2
4 1
```
**Jointable**
```
ID
1
2
3
4
5
6
```
I'm trying to output:
```
Table1Value1SUM Table2Value... | `jointable` has to be `left join`ed upon with the other 2 tables.
```
SELECT SUM(Table1.Value1) Table1Value1SUM,SUM(Table2.Value1) Table2Value1Sum
From JoinTable
Left Join Table1 On JoinTable.ID = Table1.ID
Left Join Table2 On JoinTable.ID = Table2.ID
``` | `Left Join` the `Table2` with `JoinTable` instead of `Table1`
```
SELECT SUM(Table1.Value1) Table1Value1SUM,SUM(Table2.Value1) Table2Value1Sum From Table1
Left Join JoinTable
On JoinTable.ID = Table1.ID
Left Join Table2
On JoinTable.ID = Table2.ID
``` | Left Joining Table with Sum - Causing Issues | [
"",
"sql",
"sql-server",
""
] |
I am trying to get the date part from a timestamp field.
I used this SQL query:
```
select timestamp, CAST(timestamp as date) as date from messages
```
I got the following result:
```
--------------------------------------------
| timestamp | date |
-------------------------------------------... | Use date not cast because is not casting but a format
```
select timestamp, date(timestamp) as my_date from messages
``` | Thats not a issue !!! Its only set the wrong time\_zone. see sample
**get current time\_zone**
```
SHOW GLOBAL VARIABLES LIKE 'time_zone'; -- systemwide setting
SHOW VARIABLES LIKE 'time_zone'; -- session setting
```
**sample**
```
MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+------------------... | Why does the CAST() function return the wrong date? | [
"",
"mysql",
"sql",
"date",
""
] |
Trying to use a `CASE` statement in the `WHERE` clause and it's giving me errors. What did I miss?
```
SELECT DISTINCT
Commodity,
Commodity_ID,
[Description],
Train,
Truck
FROM dbo.List_Commodity
WHERE
CASE WHEN @Truck = 1 THEN
Truck = @Truck
WHE... | Instead of `CASE` statement use `AND/OR` logic to do this
```
SELECT DISTINCT commodity,
commodity_id,
[description],
train,
truck
FROM dbo.list_commodity
WHERE ( @Truck = 1
AND truck = @Truck )
OR ( @Train = 1
AN... | If you are expecting that `THEN truck = @Truck` will return `true` or `false` then you are missing the fact that MS SQL has no boolean data type and no boolean expressions. | CASE-Statement in WHERE Clause not working what am I missing? | [
"",
"sql",
"case",
""
] |
I would like to replace a character based on its HEX value (x96) in SELECT statement.
Please help.Thanks in advance. | Hexadecimal `96` is decimal `150` the corresponding character is `chr(150)`
To remove this character from a string use the following replace (I simulate the character is the string with concatenation).
```
select replace ('test'||chr(150)||'text',chr(to_number( '96', 'xx' )), '') from dual;
testtext
``` | ASCII function returns the NUMBER code that represents the specified character.
xxxxxx - conver decimal to hex.
fm - remove trailing spaces
```
select replace('Test text to replace','e',to_char (ascii('e'), 'fmxxxxxx')) from dual
``` | SQL ORACLE: How to replace a character by its HEX value | [
"",
"sql",
"oracle",
""
] |
I was interested in writing a query for an application where I need to use a `NOT EXISTS` clause to check if a row exists.
I am using Sybase but I would like to know if there is an example in SQL in general where you can write a query having a `NOT EXISTS` clause without a nested subquery for the `NOT EXISTS`.
So ins... | You could write an anti-join using LEFT JOIN instead of an EXISTS:
```
SELECT t1.*
FROM Table1 t1
LEFT JOIN Table2 t2
ON t2.Id = t1.Id
WHERE t2.Id IS NULL
```
But with the EXISTS operator, [you *must* have a subquery](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc32300.1570/html/sqlu... | No, there is no way to use the EXISTS function in the way you are asking without a subquery. | Writing a query with a NOT EXISTS clause without a subquery for the NOT EXISTS | [
"",
"sql",
"sybase",
""
] |
I feel as if this should be quite easy, but can't seem to find a solution.
Suppose I have the following table:
```
|--------||---||---||---||---||---||---||---|
|Company ||q1 ||q2 ||q3 ||q4 ||q5 ||q6 ||q7 |
|--------||---||---||---||---||---||---||---|
|abc ||1 ||2 ||1 ||3 ||2 ||2 ||1 |
|abc ||2 ||2 |... | ```
SELECT SUM(
IF(q1 = 1, 1, 0) +
IF(q2 = 1, 1, 0) +
IF(q3 = 1, 1, 0) +
IF(q4 = 1, 1, 0) +
IF(q5 = 1, 1, 0) +
IF(q6 = 1, 1, 0) +
IF(q7 = 1, 1, 0)
)
FROM table
WHERE Company = 'abc'
``` | This is very weird assignment but:
<http://sqlfiddle.com/#!9/2e7aa/3>
```
SELECT SUM((q1='1')+(q2='1')+(q3='1')+(q4='1')+(q5='1')+(q6='1')+(q7='1'))
FROM table
WHERE Company = 'abc'
AND '1' IN (q1,q2,q3,q4,q5,q6,q7)
``` | SQL count specific value over multiple columns and rows | [
"",
"mysql",
"sql",
""
] |
I'm trying to retrive the records from a table in my MySQL database, where:
* the *timestamp* is the closest to a variable I provide; and,
* grouped by the fields keyA, keyB, keyC and keyD
I've hard coded the variable as below to test this, however can not get the query to work.
[**SQLFiddle**](http://sqlfiddle.com/... | ```
SELECT e.difference, e.timestamp, e.keyA, e.keyB, e.keyC, e.keyD, e.value
FROM (SELECT ABS(TIMESTAMPDIFF(minute, '2016-05-12 04:11:00', d.timestamp)) as difference, d.timestamp, d.keyA, d.keyB, d.keyC, d.keyD, d.value
FROM dataHistory d
ORDER BY difference) as e
GROUP BY e.keyA, e.keyB, e.keyC, e.keyD;
```
... | Does this help?
```
SELECT
TIMESTAMPDIFF (MINUTE , '2016-05-12 04:15:00' , MainTable.timestamp) AS Difference ,
MainTable.timestamp ,
MainTable.KeyA ,
MainTable.KeyB ,
MainTable.KeyC ,
MainTable.KeyD ,
MainTable.value
FROM
dataHistory AS MainTable
LEFT OUTER JOIN
dataHistory AS SecondaryTable
ON
Ma... | SQL query to retrieve records closest to timestamp | [
"",
"mysql",
"sql",
"database",
""
] |
I am not sure what I am doing to get this wrong. I am trying to get the count of usertb.id per each month. I want the 0s to be displayed if the count is null. I am using a left outer join with a month table that consists just the id of the month and name of the month. Please help. I am using SQL SERVER 2008
```
SELECT... | Well, there are a few things wrong with your query:
Firstly, do not use implicit `JOIN` syntax(comma separated) , use the proper syntax of join.
Secondly, if you do use them, don't ever mix them together with the explicit syntax, it will always lead to mistakes.
And lastly, conditions on the right table of a left jo... | Your `WHERE` clause is undoing the `LEFT JOIN`. I think this is the logic that you want:
```
SELECT monthTB.name, subTB.name
COUNT(userTB.ID)
FROM (SELECT DISTINCT subTB.sub_activity_id
FROM TDP_NetOps.dbo.sub_activity subTB
WHERE subTB.emp_id = 'xxxx'
) subTB CROSS JOIN
TDP_NetOps.dbo.mon... | Unable to get null values for the count per month | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have table for which I want to check the **count** for particular user for dates between `01/04/2016 - 17/05/2016`
I have added the query like below
```
select count(CUser_Id) from inward_doc_tracking_trl
where CSTATUS_flag = 4
and NStatus_Flag = 1
and CUser_Id = 1260
```
now how to add the `date` part and check ?... | Use `BETWEEN` to filter between two dates :
```
select count(CUser_Id) from inward_doc_tracking_trl
where CSTATUS_flag = 4
and NStatus_Flag = 1
and CUser_Id = 1260
and YourDateCol between '01/04/2016' and '17/05/2016'
```
**EDIT:** If I understood you, you need a group by clause :
```
select CUser_Id,count(CUs... | Just add the date column to the conditions list:
```
select count(CUser_Id) from inward_doc_tracking_trl
where CSTATUS_flag = 4
and NStatus_Flag = 1
and CUser_Id = 1260
and U_datetime >= '2016-04-01'
and U_datetime <= '2016-05-17'
```
Note I've used a different string format to represent dates then the one you used ... | Check count of user in a table for particular date | [
"",
"sql",
"sql-server-2005",
""
] |
I have some string output which contain alphanumeric value. I want to get only Digits from that string. how can I fetch this by query? which MySql function can I Use?
My query is like :
```
select DISTINCT SUBSTRING(referrerURL,71,6)
from hotshotsdblog1.annonymoustracking
where advertiserid = 10
limit 10;
... | If the string starts with a number, then contains non-numeric characters, you can use the [`CAST()`](http://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_cast) function or convert it to a numeric implicitly by adding a `0`:
```
SELECT CAST('1234abc' AS UNSIGNED); -- 1234
SELECT '1234abc'+0; -- 1234
```
... | To whoever is still looking, use regex:
```
select REGEXP_SUBSTR(name,"[0-9]+") as amount from `subscriptions`
``` | How to get only Digits from String in mysql? | [
"",
"mysql",
"sql",
""
] |
I'm running MySQL 5.1.71. In my database there are three tables - load, brass and mfg with load being my "main" table. My goal is to query load and have mfg.name included in the results. I've tried various iterations of `JOIN` clauses vs sub-queries both with and without `WHERE` clauses. It seems this should be pretty ... | Look at your tables and see what data relates to one another then build up joins table by table to get your desired output.
```
SELECT p.desc AS Product, m.name AS mfg
FROM product p
INNER JOIN lot l ON p.lot_id = l.id
INNER JOIN mfg m ON l.mfg_id = m.id
``` | You have an error in your join query.
Try this one:
```
Select
l.id AS "load.id",
l.brass_id AS "load.brass_id",
b.id AS "brass.id",
b.mfg_id AS "brass.mfg_id",
m.id AS "brass_mfg.id",
m.`name` AS "brass_mfg.name"
FROM `load` as l
LEFT JOIN brass as b ON l.brass_id = b.id
LEFT JOIN brass_mfg as m ON b.mfg_id... | SQL Join vs Sub-query | [
"",
"mysql",
"sql",
""
] |
I have a table where I have to get the output as follows:
```
ID - amount - TotalAmount
1 - 400 - 400
2 - 600 - 1000
3 - 400 - 1400
```
The table has two columns: ID & amount. The 'TotalAmount' should be created when the SQL script runs and hope, the rest of the sum is cleared from the above.
How c... | This is a cumulative sum. The ANSI standard method is as follows:
```
select id, amount, sum(amount) over (order by id) as TotalAmount
from t;
```
Most, but not all databases, support this syntax.
The above is the "right" solution. If your database doesn't support it, then a correlated subquery is one method:
```
s... | You didn't state your DBMS, so this is ANSI SQL:
```
select id, amount,
sum(amount) over (order by id) as totalamount
from the_table
``` | SQL query to find sum of a column | [
"",
"sql",
""
] |
I got a table with the following structure:
```
Id | clientid | type | timeStamp | message |
```
I'm using this query to get the first rows of table to start deleting rows but is crashing the DB:
```
SELECT TOP 10 [id]
,[clientid]
,[type]
,[timeStamp]
,[message]
FROM [db].[dbo].[table]
WHERE ... | I'm not sure if I understand this correctly:
If you set an index on your TimeStamp column it should be absolutely fast to filter rows greater or smaller a given date.
These lines will delete everything from your table where the TimeStamp is smaller than 2016-01-01. Only current entries will remain...
### Attention: ... | Simple?
```
WHERE timeStamp = '2014-01-01 00:00:00.000'
``` | SQL - Poor Performance SELECT Query on 377 million table | [
"",
"sql",
"sql-server",
"performance",
"bigdata",
""
] |
I referenced many questions which have the same title as mine, but they have a different approach and different issue so this question is not a duplicate.
I have a table in which `column` `fm_sctrdate` is a `date` type and has the default value `0000-00-00`.
[
Hope it helps. | You have 3 options to make your way:
1. The sql mode can be strict mode. **Go to mysql/bin/**
open my.ini or my.cnf based on windows or linux
Change **sql\_mode = "STRICT\_TRANS\_TABLES,NO\_AUTO\_CREATE\_USER,NO\_ENGINE\_SUBSTITUTION"**
To **sql\_mode= ""**
then restart mysql then **set global sql\_mode='';**
2. ... | #1292 - Incorrect date value: '0000-00-00' | [
"",
"mysql",
"sql",
"date",
"phpmyadmin",
""
] |
I have this table in SQL Server
```
name type date
aaa A 2016-05-05
aaa A 2016-05-22
aaa B 2016-05-21
bbb A 2016-05-15
bbb B 2016-05-01
```
and I want to make a query to get this result
```
name count(type)
aaa 2.5
bbb 1.5
```
NB : for A the count m... | Try this:
```
SELECT SUM(CASE type WHEN 'A' THEN 1.0 WHEN 'B' THEN 0.5 END)
FROM mytable
GROUP BY name
``` | ```
SELECT
SUM(
CASE type
WHEN 'B' THEN 0.5
WHEN 'A' THEN 1
END)
FROM <Table Name>
GROUP BY name
``` | How can I get the count depending on the column value in SQL Server | [
"",
"sql",
"sql-server",
"count",
""
] |
I'm having trouble achieving something that seems like it should be simple. The example below shows people enrolled in classes, and a person can be enrolled in multiple classes, but only one currently:
```
DECLARE @Test TABLE
(
PersonId int NOT NULL,
LocationId int NOT NULL,
ClassId int NOT NULL,
IsEnrolled bi... | I think it's a lot simpler than previously tried methods:
```
SELECT Test.*
FROM @Test Test
JOIN
(
SELECT PersonID, LocationID
FROM @Test T
WHERE ISENROLLED = 1
GROUP BY PeronID, LocationID
) T
ON Test.PersonID = T.PersonID
AND Test.LocationID = T.LocationID
```
Since y... | If I understand correctly you want all records that are either current or belong to a person who has always been in the same location. Hence:
```
select personid, classid, isenrolled, isexited
from mytable
where isenrolled = 1
or personid in
(
select personid
from mytable
group by personid
having min(locationi... | SELECT values from table with grouped id but differences in non-grouped columns | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
My problem occurs with a specific table with 3 columns.
```
itemnr --item number (int) 7 chars like 1111111
ccyymm --century year month (int) 6 chars like 201605
amount --amount of the specific item for that year month combo.
```
Basically I want to create a table that shows the amount of the past 12 months.
I creat... | ```
SELECT * FROM ITEMS WHERE CCYYMM = (year(now()) * 100 + month(now())) - 100
``` | You have tagged the question as both MySQL & SQL.
If you are using MySQL, then you could use the date functions :
```
SELECT * FROM ITEMS WHERE CCYYMM = date_format(date_sub(now(),INTERVAL 6 MONTH), '%Y%m');
``` | SQL statement not returning any values | [
"",
"sql",
""
] |
I have a table which contains datetime rows like below.
```
ID | DateTime
1 | 12:00
2 | 12:02
3 | 12:03
4 | 12:04
5 | 12:05
6 | 12:10
```
I want to identify those rows where there is a 'gap' of 5 minutes between rows (for example, row 5 and 6).
I know that we need to use `DATEDIFF`, but how can I only get tho... | You can use [**`LAG`**](https://msdn.microsoft.com/en-us/library/hh231256.aspx), [**`LEAD`**](https://msdn.microsoft.com/en-us/library/hh213125.aspx) window functions for this:
```
SELECT ID
FROM (
SELECT ID, [DateTime],
DATEDIFF(mi, LAG([DateTime]) OVER (ORDER BY ID), [DateTime]) AS prev_diff,
DA... | ## update SS2012: Use LAG
```
DECLARE @tbl TABLE(ID INT, T TIME)
INSERT INTO @tbl VALUES
(1,'12:00')
,(2,'12:02')
,(3,'12:03')
,(4,'12:04')
,(5,'12:05')
,(6,'12:10');
WITH TimesWithDifferenceToPrevious AS
(
SELECT ID
,T
,LAG(T) OVER(ORDER BY T) AS prev
,DATEDIFF(MI,LAG(T) OVER(ORDER... | Calculate Date difference between two consecutive rows | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have 8 records below:
```
ID | Common ID | Reject
-------------------------
AB-1 | AB | NULL
AB-2 | AB | YES
AB-3 | AB | NULL
BB-1 | BB | YES
BB-2 | BB | YES
BB-3 | BB | YES
CB-1 | CB | YES
CB-2 | CB | YES
DB-1 | DB | NULL
```
My expected result is:
... | ```
select min(ID), [Common ID], max(Reject)
from tablename
group by [Common ID]
having count(*) = count(case when Reject = 'YES' then 1 end)
```
If a [Common ID] has the same number of rows as the number of YES, then return it!
The `HAVING` clause's `count(*)` returns the total number of rows for a `[Common ID]`. Th... | ```
SELECT MIN(ID), CommonID, MIN(Reject) as Reject
FROM yourtable
GROUP BY CommonID
HAVING MIN(ISNULL(Reject, '')) = MAX(ISNULL(Reject, ''))
AND MIN(ISNULL(Reject, '')) = 'Yes'
```
EDIT : as you have NULL value, will need to use ISNULL() on the column | Select distinct group of records only when all of the records' certain column is of a certain value | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I need to get a result set out of a MySQL database where there are multiple pictures referenced to each item. The pictures have a picture\_no field where the lowest number is the one I want to return with the result.
Currently I am using this query:
```
SELECT
ca.*,
ca.ID AS ad_id,
ca.cat_id,
UNIX_TI... | You could use this:
```
SELECT
ca.*,
ca.ID AS ad_id,
ca.cat_id,
UNIX_TIMESTAMP(ca.date_edited) AS date,
cp.*,
ar.area_name
FROM
$DB.$T4 ca
LEFT JOIN (SELECT tmp.*
FROM $T6 tmp
INNER JOIN (SELECT classified_id, MIN(picture_no) min_picture_no
... | You could change the join into something like this:
```
LEFT JOIN (select * from $T6 AS cp where ca.ID = cp.classified_id order by picture_no asc limit 1) on ca.ID = cp.classified_id
``` | How to get MySQL result set with lowest picture number? | [
"",
"mysql",
"sql",
""
] |
I have two tables with the following structure:
```
|=================|
| posts |
|=================|
| ID | Title |
|-----------------|
| 1 | Title #1 |
|-----------------|
| 2 | Title #1 |
|-----------------|
| 3 | Title #1 |
|-----------------|
| 4 | Title #1 |
|-----------------|
| 5 | ... | <http://sqlfiddle.com/#!9/af591f/4>
```
SELECT
`b`.`id` AS `ID`,
`b`.`title` AS `Title`,
mt1.meta_value `KeyOne`,
mt2.meta_value `KeyTwo`,
mt3.meta_value `KeyThree`
FROM
`base` as `b`
LEFT JOIN `meta` mt1 ON b.id = mt1.base_id AND mt1.meta_key = 'key_one'
LEFT JOIN `meta` mt2 ON b.id = mt2.base_id A... | You can use *conditional aggregation* for this:
```
SELECT p.ID, p.Title AS 'Post Title',
MAX(CASE WHEN meta_key = 'key_one' THEN meta_value END) AS 'Meta Key One',
MAX(CASE WHEN meta_key = 'key_two' THEN meta_value END) AS 'Meta Key Two',
MAX(CASE WHEN meta_key = 'key_three' THEN meta_value END) ... | How to join those two tables in MySQL | [
"",
"mysql",
"sql",
""
] |
There is DDL script in PostgreSQL that creates tables.
For example, if first table exists,
**How to stop SQL script execution for PostgreSQL (within script)?** | If you want to abort a script based on a condition you can do that using a `DO` block that raises an error:
```
do
$$
declare
l_count integer;
begin
select count(*)
into l_count
from information_schema.tables
where table_name = 'foobar'
and table_schema = 'public';
if (l_count > 0) then
rai... | You can do something like this:
```
SELECT 'Step 1' as step;
DO $$
BEGIN
assert (SELECT 'B'::text) = 'A'::text, 'Expected A';
END;
$$;
SELECT 'Step 2' as step;
```
Returns:
```
ERROR: Expected A
CONTEXT: PL/pgSQL function inline_code_block line 3 at ASSERT
SQL state: P0004
```
You can use any type to co... | How to stop SQL script execution for PostgreSQL? | [
"",
"sql",
"postgresql",
""
] |
I was trying to create a view and needed to create a column that shows if the 'somenumber' column exists on other table or not. The code below worked but very slowly. Is it possible to declare a table as (select someNumber from veryYugeTable) and check on that one instead of sending this query for every single record o... | You might find you get some benefit with scalar subquery caching if you do something like:
```
coalesce((select 'exists'
from veryyugetable vyt
where vyt.somenumber = someOtherTable.someNumber
and rownum = 1),
'doesn''t exist') somecolumn
```
N.B. the `and rownum = 1` is n... | The query looks fine. You should have an index on `veryYugeTable.someNumber`.
Sometimes the optimizer handles correlated subqueries better than non-correlated ones, so you can try:
```
case
when exists
(
select *
from veryYugeTable
where veryYugeTable.someNumber = someOtherTable.someNumber
) then ... | Oracle 11g, how to speed up an 'in' query | [
"",
"sql",
"oracle",
"if-statement",
"view",
"oracle11g",
""
] |
I want to check which users have the most records in a database. So every user has a specific Id, and that Id is used as a reference in a few tables.
There are a few tables that contain a column UserId, like the table Exams, Answers, Questions, Classes, etc. Is it possible to count all the records with a specific User... | ```
;with cte as (
select rowsCount = count(*) from A where UserId = 1
union all
select rowsCount = count(*) from B where UserId = 1
union all
select rowsCount = count(*) from C where UserId = 1
)
select sum(rowsCount) from cte
``` | I would do it in this way:
```
With AllRecords AS
(
SELECT TableName = 'Exams'
FROM dbo.Exams
WHERE UserId = @YouruserID
UNION ALL
SELECT TableName = 'Answers'
FROM dbo.Answers
WHERE UserId = @YouruserID
UNION ALL
SELECT TableName = 'Questions'
FROM dbo.Questions
WHERE UserI... | How to get amount of records of a specific ID in a database? | [
"",
"sql",
"sql-server",
""
] |
I'm trying to aggregate a list of product skus with a query that relates through a line\_items table. I've abstracted a simple example of my use case:
**my expected result would look like this:**
```
id name skus
1 mike bar sku1,sku2,sku3
2 bort baz sku4
```
given a schema and data like:
products
... | You can use a correlated subquery with a `JOIN` to get the list of `sku`s for each `order`
```
SELECT
o.id,
a.name,
(SELECT array_to_string(array_agg(sku), ',') AS Skus
FROM products p
INNER JOIN line_items li
ON li.product_id = p.id
WHERE li.order_id = o.id
) AS Skus
FROM orders... | <http://sqlfiddle.com/#!15/70cd7/12>
```
SELECT orders.id,
addresses.name,
array_agg(DISTINCT products.sku )
FROM orders
LEFT JOIN addresses
ON orders.address_id = addresses.id
LEFT JOIN line_items
ON line_items.order_id = orders.id
LEFT JOIN products
ON products.id = line_items.product_id
GROUP BY ord... | SQL aggregate query with one-to-many relationship with postgres | [
"",
"sql",
"postgresql",
"postgresql-9.3",
""
] |
I have a stored procedure that select top X from Table,
```
declare @i int ;
set @i = 10 ;
select top @i from tableNam
```
> Incorrect syntax near '@i'.
What should i do ?
suppose that the @i comes from parameters in my storedProcedure | You have to enclose the variable in parenthesis to make it work.
```
declare @i int ;
set @i = 10 ;
select top (@i) * from tableNam
```
If you take the cursor to the error line you will find the reason as to why you need the parenthesis like this:
[... | Following syntax will work
```
declare @i int ;
set @i = 10 ;
select top (@i) * from sys.tables
``` | Sql server use variable in selection top row | [
"",
"sql",
"sql-server",
""
] |
I want to use postgresql `to_number(numberString, format_mask)`. My numberString may contain leading zeros (I don't know the actual length of these zeros and the numberString in total). I want to trim these zeros and get the value as number.
I've read about this function [here](http://www.techonthenet.com/postgresql/f... | You don't need `to_number()` for this. Just cast the string to an integer:
```
select '00005469'::integer;
```
or using standard SQL:
```
select cast('00005469' as integer);
``` | To be more safe if your column has decimals or not, use
```
select NULLIF('00005469', '')::decimal
```
This `select '00005469'::integer;` will not work if there are decimals | Postgresql to_number() function format | [
"",
"sql",
"postgresql",
"type-conversion",
"sqldatatypes",
""
] |
How to encapsulate Between statement in SQL server.
I have a lot of code to refactor that has long list of where clauses with the same Between statement that have magic numbers and I want to refactor it. It is possible to encapsulate the BETWEEN.
Example: The query has something similar like this and there is not pos... | If you want a function you can do it.
```
create function dbo.isValid(val int)
returns int
as
begin
if val BETWEEN 3456 AND 15500
return 1
return 0
end
```
And obvious usage:
```
select * from table1
where dbo.isValid(id) = 1
``` | As @Rion said either create variables or use a seperated table
```
CREATE TABLE check_range
("range_id" int, "begin" int, "end" int)
;
INSERT INTO check_range
("range_id", "begin", "end")
VALUES
(1, 3456, 15500)
;
```
Then your query should be
```
SELECT ...
FROM Table0
CROSS JOIN check_range cr
WHERE I... | How to encapsulate Between statement in SQL server | [
"",
"sql",
"between",
""
] |
My example query is:
```
SELECT
tab1.col1, tab2.col1, tab3.col2
FROM
tab1 JOIN tab2 ON tab1.col1=tab2.col1
left JOIN tab3 ON tab1.col2=tab3.col2
WHERE blah blah GROUP BY blah blah HAVING blah blah;
```
I want to apply a condition (such as a `"where" or "having"` to just one of the joins but not the ot... | There are multiple ways to achieve that
First would be to simply put the filter clause at the end of the query. Mostly this must produce same results, although in some cases, this might not be the case.
```
SELECT
tab1.col1, tab2.col1, tab3.col2
FROM
tab1
JOIN
tab2
ON tab1.col1=tab2.co... | ```
SELECT
tab1.col1, tab2.col1, tab3.col2
FROM
(select * from tab1 where / having) tab1 JOIN tab2 ON tab1.col1=tab2.col1
left JOIN
(select *from tab3 where / having) tab3 ON tab1.col2=tab3.col2
```
Is this what you want? | how can I apply a condition to just one part of a multiple join in SQL? | [
"",
"sql",
"join",
"conditional-statements",
"where-clause",
"having",
""
] |
I have a table with values:
```
--Product--
ASUS22
ASUSI522
ASUSI7256
ASUSI2262
ASUSI1267
ASUSI764
ASUSI712
```
and so on. I'm trying to select products with it starting with ASUSI and only 3 integers after it.
Somebody said I can use \d\d\d in order to achieve that but it doesn't work(below)
```
select product fro... | In order to use character classes, you need to use `SIMILAR TO` instead of `LIKE`:
```
select product from products where product similar to '%ASUS\d\d\d'
```
As @lad2025 notes, your original query does not match your expectation, so you need remove the final `%` to restrict the match to three numbers. | The regular expression you want to match the string `ASUSI` with exactly three digits after it is:
```
^ASUSI\d{3}$
^ASUSI - starts with 'ASUSI'
\d{3} - followed by exactly three digits
$ - followed by the end of the string
SELECT product
FROM products
WHERE product ~ '^ASUSI\d{3}d$'
``` | Selecting values using \d | [
"",
"sql",
"postgresql",
""
] |
I have a select statement that gives a set of rows whose count is always a multiple of 8.
What I want to do is to find the sum of the first 8 rows, the second 8 rows and so on. Is there a way to do this | ```
select a from test;
select r/8, SUM(a) from (select ROW_NUMBER() over (order by a)-1 as r,a from test) tab group by r/8;
```
[](https://i.stack.imgur.com/kz53i.jpg)
```
update test set a=t2.v
from test t1,(select (ROW_NUMBER() over (order by a)-... | Ideal: You declare `groups of 8 rows` by geting `row number` of all rows, subtract by 1 then divine by 8 . Then you calculate sum of those group that you just declare
Assume that your original query is
```
select col1, col2, ..., value1, value2,...
from table
order by col1, col3,...
```
You could use this:
```
se... | How to sum 8 rows at a time in a select statement | [
"",
"sql",
"sql-server",
""
] |
I have a parent model **Post** and a child model **Comment**. Posts have privacy setting - column `privacy` in the DB. Any time when I have to deal with a child model **Comment** I have to check privacy settings if the parent model: `$comment->post->privacy`.
My app is becoming bigger and bigger and such approach need... | Planned redundancy (denormalization of the model) for a specific purpose can be good.
You specifically mention keeping the `privacy` column on the child table "in sync" with the `privacy` column in the parent table. That implies you have control of the redundancy. That's acceptable practice, especially for improved pe... | Assuming that the privacy properties have to be in the parent (if the "Post" are not used directly on its own you can always move the property "privacy" to all the children)
**First** you should try enhance the performance using optimization techniques (like indexes, materialized views.. etc.)
**Second** if that di... | Duplicating columns from parent to child model. Good or bad practice? | [
"",
"mysql",
"sql",
"laravel",
"optimization",
""
] |
I am fairly new to SQL and am having some trouble with the last step in a slightly complicated SQL Query. I want to count how many times in the table, two distinct values appear in more than 1 row.
My specific scenario is, that my table stores Messages/Alerts too and from a system. These alerts are sent to multiple pe... | You can do this using a `CASE` expression inside `COUNT`.
```
SELECT
AlertID,
Replies = COUNT(DISTINCT CASE WHEN SentBy <> 'mySystem' THEN RecepientID END)
FROM alerts
GROUP BY AlertID
```
`ONLINE DEMO` | First, don't use `select distinct` when you should be using `group by`.
Then this produces the results you seem to want:
```
SELECT AlertID, (count(Distinct RecipientID) - 1) as Replies
FROM [myDB].[dbo].[Alerts]
GROUP BY AlertId;
```
You might actually want:
```
SELECT AlertID, count(Distinct case when sentBy <... | Count number of times 2 distinct values appear in more than 1 row in SQL Table | [
"",
"sql",
"sql-server",
"vb.net",
"count",
""
] |
I'm wondering if there is better,more optimal way to retrieve a number from string
eg.
```
"O5_KK/text1/1239312/006_textrandom"
"O5_KK/text1/1239315/0109_textrandom123"
"O5_KK/text1/1239318/0110_textrandom432"
'O5_KK/text1' - hardcoded, never change.
1239312,1239315,1239318 - random number, unique within row
textrand... | You can use `regexp_subtr()`:
```
select regexp_substr(val, '/[0-9]+_', 1, 1)
```
And then remove the extra characters:
```
select replace(replace(regexp_substr(val, '/[0-9]+_', 1, 1), '/', ''), '_', '')
``` | This is simply the part after the third slash before the second underscore:
```
substr(str, instr(str, '/', 1, 3) + 1, instr(str, '_', 1, 2) - instr(str, '/', 1, 3) - 1)
``` | Retrieve number from string most effective way | [
"",
"sql",
"oracle",
""
] |
[SQL FIDDLE DEMO HERE](http://%20%20[1]:%20http://sqlfiddle.com/#!6/4c7c2)
I have this table structure for Workers table:
```
CREATE TABLE Workers
(
[Name] varchar(250),
[IdWorker] varchar(250),
[work] varchar(250)
);
INSERT INTO Workers ([Name], [IdWorker], [work])
values
('Sam', '001', 'D... | I am assuming in your example query you meant job to reference the work column. The following query should do the job as per your sql fiddle.
```
SELECT STUFF(
(
SELECT ', ' + cast([Name] as varchar(max))
FROM Workers
... | the way you would do this using PIVOT would be like this.
```
SELECT *
FROM (SELECT [work],
STUFF((SELECT ', ' + [Name]
FROM Workers s
WHERE s.WORK = w.WORK
FOR XML PATH('')),
1, 2, '') AS [worke... | How can I join together this querys sql server? | [
"",
"sql",
"sql-server",
"join",
"pivot",
"coalesce",
""
] |
Im just writing a query to look through my clients customers database and to list how many orders they have made etc.
What I'm struggling to add into this query is to only show me most recent OrderID for that email
Any ideas?
Here is my query
```
select top 1000
BuyerEMail
,COUNT(*) HowMany
,Name
fr... | Give this a go;
```
SELECT TOP 1000
o.BuyerEMail
,COUNT(*) HowMany
,o.Name
,o2.OrderID
FROM Orders o
JOIN
(
SELECT
BuyerEmail
,MAX(OrderDate) Latest
FROM Orders
GROUP BY BuyerEmail
) l
ON o.BuyerEmail = l.BuyerEmail
JOIN Orders o2
ON l.BuyerEmail = o2.BuyerEmail
AND l.OrderDate =... | If you are having troubles writing sql queries, try to break up your needs into single statements.
First you wanted the number of orders per buyer, which you already solved.
```
SELECT BuyerEMail
, Name
, COUNT(*) as TotalOrders
FROM Orders
WHERE Pay <> 'PayPal'
GROUP BY BuyerEmail, Name
Order By TotalOrders Desc
```... | SQL most recent order? MS SQL | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.