Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a table named Articles, which suprisingly has a column named Article, which is the Primary Key.
In this column all articles used to be designated with an unnecessary prefix which I am tasked to remove.
Examples:
1-184-W21TK00032
1-154-MXA0074
In these examples both 184 and 154 designate distributors, they al... | The problem occurs because `LEN(Article)` is less than 6 for at least 1 row which means you are passing a negative value into the `SUBSTRING`. Filter them out using `WHERE LEN(Article) > 6` | It's probably not the WHERE you're changing that is the issue.
There are probably rows for "154" where the other SUBSTRING fails.
That is, there are probably (Len(Article) - 6) < 0.
Search for that to confirm and then add a CASE or such to manage it. | Issues when using SUBSTRING to trim the first 6 characters in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I am using TRY CATCH block to capture error and do rollback
```
ALTER PROCEDURE sp_first
/*
parameters
*/
BEGIN TRY
BEGIN TRANSACTION
/*
statements
*/
COMMIT
END TRY
BEGIN CATCH
IF(@@TRANCOUNT>0)
ROLLBACK
END CATCH
```
Will the above approach work if there is another stored procedure `sp_inner` being called i... | `rollback` rolls back to the outermost transaction, not just the current transaction within a transaction. If that is what you are trying to do, then it will work. If not, then it won't.
See General Remarks at <http://msdn.microsoft.com/en-us/library/ms181299.aspx> | I would recommend checking [this link](http://technet.microsoft.com/en-us/library/ms178157(v=sql.100).aspx) for an example. Basically, as podiluska said, a standard rollback will rollback the entire transaction (meaning, you could have a trancount of 5 and it'll revert all those changes).
You could check the trancount... | Implement rollback in Nested stored procedure | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
Similar to this question : [SQL Statement with multiple SETs and WHEREs](https://stackoverflow.com/questions/6446250/sql-statement-with-multiple-sets-and-wheres)
Is there a way to perform multiple sets, as shown below.
```
UPDATE table
SET ID = 111111259
SET Name = "Bob"
SET Phone = 1111111261
WHERE ID = 2555
```
T... | This is possible,
```
UPDATE table SET Name = 'aaa', Col2 = 'bbb' WHERE ID IN (2555, 2666)
```
What you are asking for is setting multiple values to same column and same row. | No need of `SET` for each column. do it like
```
UPDATE table
SET ID = 111111259,
Name = 'Bob',
Phone = 1111111261
WHERE ID = 2555
``` | SQL multi SET with one WHERE | [
"",
"sql",
"database",
"set",
"where-clause",
""
] |
I have following query to select the view to be used in the query, however I get the error:
> FROM keyword not found where expected
```
select *, (CASE WHEN 'employee' = 'employee' THEN employee ELSE vw END) FROM type1
``` | ```
select type1.*,
(CASE WHEN 'employee' = 'employee'
THEN employee
ELSE vw
END)
FROM type1
```
I always *prefix* with the tablename/table alias to the `*` and it works!!
We just need to specify, fetch `all` the column from `this` table, when we specify combination of wildcard ... | You cannot use `*` and individual columns together in select statement.
```
SELECT (CASE WHEN 'employee' = 'employee' THEN 'employee' ELSE 'vw' END)
FROM dual
``` | CASE SQL Oracle Query - What is wrong? | [
"",
"sql",
"oracle",
"case",
""
] |
I have a table with the following columns:
```
ID | NAME | ID_PREVIOUS | ID_FOLLOWING | RANDOM_USELESS_DATA
----+--------+--------------+--------------+---------------------
1 | AB2-F | NULL | 2 | bla bla bla
2 | PP-01 | 1 | 3 | ffwfwqafrwf
3 | 10J6U | ... | ```
SELECT T.NAME,
TP.NAME AS NAME_PREVIOUS,
TF.NAME AS NAME_FOLLOWING
FROM YOUR_TABLE AS T
LEFT JOIN YOUR_TABLE AS TP TP.ID = T.ID_PREVIOUS
LEFT JOIN YOUR_TABLE AS TF TF.ID = T.ID_FOLLOWING
```
That's general SQL that should work for the most DBMS I suppose, however as I know Access query builder for some reasons a... | If you only have a single level of "previous/following" you can get away with a self-join
```
select nd.name,
pr.name as name_previous,
nx.name as name_following
from nodes nd
left join nodes pr on nd.id_previous = pr.id
left join nodes nx on nd.id_following = nx.id;
```
SQLFiddle: <http://sqlfidd... | SQL - query and replace column value with another value extracted from the same table | [
"",
"sql",
""
] |
I want to retrieve all the values from a table in which email ID are not repeated. But when I run below query the execution goes into infinite in mysql.
```
SELECT * FROM USERS
WHERE EMAIL IN (
SELECT EMAIL
FROM USERS
GROUP BY EMAIL
HAVING COUNT(1) = 1)
```
I don't understand why this query i... | This should work as-is, but you might try to rewrite it to a Join instead, MySQL's optimizer is not that clever :-)
```
SELECT u.*
FROM USERS AS u
JOIN ( SELECT EMAIL FROM USERS GROUP BY EMAIL HAVING COUNT(1) = 1) AS dt
ON u.EMAIL = dt.email
``` | This is one case where the MySQL extension on `group by` comes in handy. You can do this query as:
```
select u.*
from users u
group by email
having count(*) = 1;
```
The MySQL extension allows you to include columns in the `select` that are not in the `group by`. The values come from arbitrary (the documentation say... | How find values not duplicate in mysql | [
"",
"mysql",
"sql",
""
] |
```
------------------------------------
X Y
------------------------------------
10 20
10 5
10 9
50 40
50 30
100 70
100 100
```
Consider 1 ,2 , 3 rows as Group A
and 4,5 rows as Group B
and 6,7 rows as Group C
I want to get a only one row for a ... | You can do this with conditional aggregation:
```
select x, max(case when y <= x then y end) as y
from table t
group by x;
``` | Alternative solution
```
DECLARE @tb TABLE (
X float , Y float
)
INSERT INTO @tb (X,Y) values
(10, 20),
(10, 5),
(10, 9),
(50, 40),
(50, 30),
(100, 70),
(100, 100);
select a.* from (
select row_number() over( partition by X order by abs(X-Y) asc ) as rn, X, Y
from @tb
) a where a.rn = 1;
``` | Get only rows that nearest lower in Y column to X column | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I get this Error
---
```
07-16 20:58:27.299: E/AndroidRuntime(14005): Caused by: android.database.sqlite.SQLiteException: no such table: strings: , while compiling: SELECT id, string FROM strings WHERE id = ?
```
---
I hava StringDB class that has ID and String to store objects of this class into SQLite Database. ... | 1. Under `private static final String DATABASE_NAME = "StringDB";` add
```
private static final String TABLE_NAME = "strings";
```
2. Change `String CREATE_StringDB_TABLE = "CREATE TABLE StringDBs ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +"string"+ "TEXT )";`
to
```
String CREATE_StringDB_... | You are passing the wrong table name. You are creating `StringDB` and asking for `strings` | Caused by: android.database.sqlite.SQLiteException: no such table: strings: , while compiling: SELECT id, string FROM strings WHERE id =? | [
"",
"android",
"sql",
"sqlite",
""
] |
I have a stored procedure that will accept 2 different parameters. The first parameter will determine which column I want to sort on, the second parameter will determine whether it is `ASC` or `DESC`
```
Create Procedure Some_SP
@sortcolumn varchar(10)
@sortorder varchar(10)
AS
Select * from empTable
O... | The following will work:
```
Select * from empTable
Order by
CASE WHEN @sortcolumn = 'First_Name' AND @SortOrder = 'ascending' THEN fname END ASC,
CASE WHEN @sortcolumn = 'First_Name' AND @SortOrder = 'descending' THEN fname END DESC
```
etc...
In order to avoid typing each of these case statements by hand, you coul... | If you want to avoid dynamic SQL and using 2x your conditions, you can use `row_number`
eg:
```
declare @t table (string varchar(50), number int)
insert @t values ('a',9),('f',2),('c',1)
declare
@sc varchar(10) = 'number', -- or 'string', etc
@so varchar(10) = 'desc' -- or 'asc'
select *
from
(
selec... | SQL Case with 2 conditions | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
how can I select Julian day of year in Oracle database?
I tried:
select to\_char(sysdate, 'J') from dual;
Which gives me the number of days since January 1, 4712 BC. But I would need the number of days since 1.1. of current year. | If you check the [TO\_CHAR (datetime)](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions180.htm) documentation you get a link to ["Format Models"](http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm#i34510) with a comprehensive list of available formats. I guess you want this:
> `DD... | ```
SELECT TO_CHAR(SYSDATE, 'DDD') from DUAL;
``` | Oracle Julian day of year | [
"",
"sql",
"oracle",
"julian-date",
""
] |
I'm making a table in SSRS that contains customer names in column 1 and their corresponding number of orders in column 2. This query works for what I'm trying to accomplish, but I don't know exactly how the Count function knows what the heck I want it to count and what table I'm wanting it to count from. Could someone ... | > I don't know exactly how the Count function knows what the heck I want it to count
There is only one thing that `COUNT` is able to count - it can count *rows* in which an expression evaluates to a non-null value. If you use `COUNT(1)` in a regular query, you would get `1` on each row. With `GROUP BY`, however, the `... | Count is counting `true` for each record found. Therefore, if there are 3 records, it is counting `true` 3 times and returns `3`. It doesn't really matter what it is counting in there as long as it exists or is a constant. If it exists, it is counted. It's the number of rows that you are being grouped when you group by... | Could someone explain how Count works in this SQL query? | [
"",
"sql",
"sql-server",
"reporting-services",
""
] |
I am trying to Execute a stored procedure that requires to variables be passing into to it. One is a static, the other is a dynamic variable.
```
DECLARE @Filt DATETIME
SET @Filt = (SELECT DISTINCT MAX(Date) FROM Data.db.Staging)
SELECT * INTO #tempData FROM OPENROWSET('SQLNCLI', 'Server=ISR14 \MSSQL2012;Trusted_Con... | You have to put the whole statement into a variable and run it, and convert @FilterData to a varchar to concatenate it.
You can't use variables with openquery/openrowset.
Try this and check the print output... if it works and looks ok, then EXEC(@sql2)
```
DECLARE @FilterData DATETIME
DECLARE @sql VARCHAR(200), @sql... | You need to make the whole query dynamic, not sure if I got it nailed down, but something like:
```
DECLARE @Filt DATETIME
,@sql VARCHAR(MAX)
SET @Filt = (SELECT MAX(Date) FROM Data.db.Staging)
SET @sql = 'SELECT * INTO #tempData FROM OPENROWSET(''SQLNCLI'', ''Server=ISR14 \MSSQL2012;Trusted_Connection=yes;''... | Syntax issue in SQL Server, using OPENROWSET | [
"",
"sql",
"sql-server",
"t-sql",
"concatenation",
"openrowset",
""
] |
I have a question about separating variables in a data set in a specific way. When we did field work, we had to collect data in a method that looked like this:
```
Range Row HGT V HGT2 V2 HGT3 V3 HGT4 V4
1 2 151 15 127 22 114 16 97 12
```
In reality, the variables there are not different ty... | If the the number of variables are certain then you can follow this method.
Assumption: Source data is "Range\_data"
```
data Range_data_1(keep=Range Row HGT V);
set Range_data;
run;
data Range_data_2(keep=Range Row HGT2 V2);
set Range_data;
run;
data Range_data_3(keep=Range Row HGT3 V3);
set Range_data... | Does this help?
```
SELECT RANGE, ROW, HGT, V, NULL AS HGT2, NULL AS V2, NULL AS HGT3, NULL AS V3, NULL AS HGT4, NULL AS V4
UNION
SELECT RANGE, ROW, NULL AS HGT, NULL AS V, HGT2, V2, NULL AS HGT3, NULL AS V3, NULL AS HGT4, NULL AS V4
UNION
SELECT RANGE, ROW, NULL AS HGT, NULL AS V, NULL AS HGT2, NUL... | Separating variables in a SAS data set | [
"",
"sql",
"sas",
""
] |
I have a table like
```
create table temp_table (col1 int)
```
I have some data in this table like
```
insert into temp_table
values(1), (2), (3), (4)
```
Now I want the data to be output as follows:
```
1,2,3,4
```
I have used the query:
```
select cast(col1 as nvarchar)+','
from temp_table
for xml path('')
... | ```
declare @temp nvarchar(max)
select @temp = COALESCE(@temp + ', ', '') + CAST(col1 as nvarchar) from temp_table
select @temp
``` | And if you really don't get it with the given link :
```
select STUFF((
SELECT ',' + cast(col1 as nvarchar)
FROM temp_table
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
``` | Merge data many rows of one column into a single row in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have two tables in a MS Sql Server database, imported from different sources, that I want to merge.
### Table1:
```
Id: int identity primary key
Name: varchar(50)
Code: varchar(50)
```
### Table1 Data:
```
Id, Name, Code
1, 'Knife', '1'
2, 'Spoon', '1'
3, 'Fork', '1'
...
```
### Table2:
```
Code: varc... | Added row numbers to the base tables and joined on that. The below code works.
```
update t1
set t1.code = t2.code
from
(select *, row_number() over(order by id) as rNum1 from table1) t1
join
(select *, row_number() over(order by code) as rNum2 from table2) t2
on t1.rnum1 = t2.rnum2
``` | If there are the same number of rows in each table and it doesn't matter which code goes against which record then why not create an arbitrary key field using row number within a sub query and then join on that?
```
SELECT
TABLE1.ID,
TABLE1.Name,
TABLE2.Code
FROM
(SELECT ROW_NUMBER() OVER (ORDER BY ID... | Merging table data without keys to join on | [
"",
"sql",
"sql-server-2008",
"join",
"merge",
"updates",
""
] |
I am having a bit of trouble when modelling a relational database to an inventory managament system. For now, it only has 3 simple tables:
1. Product
```
ID | Name | Price
```
2. Receivings
```
ID | Date | Quantity | Product_ID (FK)
```
3. Sales
```
ID | Date | Quantity | Product_ID (FK)
... | Personally I prefer the first option, that is, separate tables for `Sales` and `Receiving`.
The two biggest disadvantage in option number 2 or merging two tables into one are:
```
1) Inflexibility
2) Unnecessary filtering when use
```
First on inflexibility. If your requirements expanded (or you just simply overlook... | ***If*** the tables really are and always will be identical (and I have my doubts), then name the unified table something more generic, like "InventoryTransaction", and then use negative numbers for one of the transaction types: probably sales, since that would correctly mark your inventory in terms of keeping track of... | Turn two database tables into one? | [
"",
"sql",
"database",
"database-design",
"orm",
""
] |
I have 2 tables called Orders and Salesperson shown below:

And **I want to retrieve the names of all salespeople that have more than 1 order from the tables above**.
Then firing following query shows an error:
```
SELECT Name
FROM Orders, Salesperson
WHERE Orde... | ```
SELECT max(Name) as Name
FROM Orders, Salesperson
WHERE Orders.salesperson_id = Salesperson.ID
GROUP BY salesperson_id
HAVING COUNT( salesperson_id ) >1
```
The basic idea is that columns that are not in the group by clause need to be in an aggregate function now here due to the fact that the name is probably the ... | Assuming the name is unique to the salesperson.id then simply add it to your group by clause
```
GROUP BY salesperson_id, salesperson.Name
```
Otherwise use any Agg function
```
Select Min(Name)
```
The reason for this is that SQL doesn't know whether there are multiple name per salesperson.id | wrapping inside aggregate function in SQL query | [
"",
"mysql",
"sql",
"group-by",
"aggregate-functions",
""
] |
Why does this give me 1 which is what I was expecting:
```
IF (SELECT 123) = 123
PRINT 1
ELSE
PRINT 2
```
But this gives me 2 which I was not expecting:
```
IF (SELECT NULL) = NULL
PRINT 1
ELSE
PRINT 2
``` | `NULL` values are checked by `IS NULL`
you have to use:
```
IF (SELECT NULL) IS NULL
PRINT 1
ELSE
PRINT 2
```
from the [manual](http://dev.mysql.com/doc/refman/5.7/en/problems-with-null.html):
> To search for column values that are NULL, you cannot use an expr =
> NULL test. The following statement returns ... | If you put NULLS OFF
```
SET ANSI_NULLS OFF
IF (SELECT NULL) = NULL
PRINT 1
ELSE
PRINT 2
```
then you will get PRINT 1 | SQL IF NULL From SELECT statement | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I've got the following MySQL query:
```
SELECT user_id, score, time
FROM tests_1 T
WHERE T.score = (
SELECT MAX(T2.score)
FROM tests_1 T2
WHERE T2.user_id = T.user_id
)
ORDER BY score DESC, time ASC;
```
How do I add the 'username' column from the 'users' table ON users.user\_id = tests\_1.user\_id? | Try this:
```
SELECT T.user_id, U.username, T.score, T.time
FROM tests_1 T
JOIN users U on U.user_id = T.user_id
WHERE T.score = (
SELECT MAX(T2.score)
FROM tests_1 T2
WHERE T2.user_id = T.user_id
)
ORDER BY T.score DESC, T.time ASC;
``` | Just join it.
```
SELECT T.user_id, T.score, T.time, u.username
FROM tests_1 T
JOIN users u ON u.user_id = T.user_id
WHERE T.score = (
SELECT MAX(T2.score)
FROM tests_1 T2
WHERE T2.user_id = T.user_id
)
ORDER BY T.score DESC, T.time ASC;
``` | MySQL - WHERE clause + JOIN | [
"",
"mysql",
"sql",
"subquery",
""
] |
I can select and pull out a list of records by using a select statement like so with t-sql:
```
select * from [dbo].[testTable];
```
But how can I add in a "custom" row to the top of the result set?
For example, if the result set was:
```
John john@email.com
Max max@domain.com
```
I want to add a row, which... | This is the safe way to do this:
```
select name, email
from ((select 'name' as name, 'email' as email, 1 as which
) union all
(select name, email, 2 as which from [dbo].[testTable]
)
) t
order by which;
```
In practice, `union all` will work:
```
select 'name' as name, 'email' as email
... | ```
SELECT name, email FROM (
SELECT 'Name' AS Name, 'Email' AS Email, 1 AS o
UNION ALL
SELECT name, email, 2 AS o FROM testTable
) t
ORDER BY o, name
```
The o column is added to order the result sets of the UNION so that you ensure the first result set appears on top. | How can I add a "custom" row to the top of a select result set? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
For some reason the developer create the date column in my DB as a string and it is stored as `YYYY_MM_DD`.
Does anyone know how I can convert the `YYYY_MM_DD` to a date field via SQL. e.g
```
2014_06_30 to 30/6/2014.
```
Or any other solutions
Thank you in advance | Please try:
```
DECLARE @str NVARCHAR(100)='2014_06_30'
select CONVERT (DATETIME, REPLACE(@str, '_', '-'))
```
To convert it to format 30/6/2014, try:
```
select CONVERT(NVARCHAR(20), CONVERT(DATETIME, REPLACE(@str, '_', '-')), 103)
``` | ```
var myDate = '2014_06_30';
var myNewDate = select CONVERT (datetime, Replace(myDate,'_','/'))
``` | convert String YYYY_MM_DD to date | [
"",
"sql",
"sql-server",
"datetime",
""
] |
I am attempting to use multiple aggregate functions across multiple tables in a single SQL query (using Postgres).
My table is structured similar to the following:
```
CREATE TABLE user (user_id INT PRIMARY KEY, user_date_created TIMESTAMP NOT NULL);
CREATE TABLE item_sold (item_sold_id INT PRIMARY KEY, sold_user_id ... | The easy fix to your query is to use `distinct`:
```
SELECT user_id, COUNT(distinct item_sold_id), COUNT(distinct item_bought_id)
FROM user
LEFT JOIN item_sold ON sold_user_id=user_id
LEFT JOIN item_bought ON bought_user_id=user_id
WHERE user_date_created > '2014-01-01'
GROUP BY user_id;
```
However, the query is doi... | [SQL Fiddle](http://sqlfiddle.com/#!15/adc79/1)
With a lateral join it is possible to pre aggregate only the filtered users
```
select user_id, total_item_sold, total_item_bought
from
"user" u
left join lateral (
select sold_user_id, count(*) as total_item_sold
from item_sold
where sol... | Using SQL Aggregate Functions With Multiple Joins | [
"",
"sql",
"postgresql",
"join",
"left-join",
"aggregate-functions",
""
] |
1. If a row in a table (without primary key) is locked when some modification(update query) is taking place for that row, I assume that the intent locks are first acquired on table, then page before the exclusive lock is acquired on the row.
Now let's say that some other thread wishes to make modification(update qu... | > 1. might be the reason that the other row of the same table was amongst the data locked in the same data page of the first query?
No. If both queries use the same granularity (eg. row) then they will obtain compatible intent locks at the high levels (table(partition), page) and different locks at the low (row) level... | There are multiple kinds of locks in SQL Server, for different "granularities" of data.
In a perfect world, if you only update one row, indeed it could only hold a row lock and any other row would not be locked.
The engine reserves the right to "escalate" a lock to a larger set, such as a page or even a whole table. ... | SQL Server deadlock and Data Pages | [
"",
"sql",
"sql-server",
""
] |
Using the excellent [tSQLt](http://tsqlt.org/) testing framework (v1.0.5137.39257) for MS SQL Server (2012), I'm trying to build a test to check that a UNIQUE INDEX works and generates an exception when a duplicate value is inserted.
After extensive searching, I cannot find a way to apply an index to a table that has ... | Could you not create a unique constraint instead? You'll still get the desired index under the hood. tSQLt.ApplyConstraint works for unique keys the same as it does for primary keys - but only in the very latest version IIRC. For example:
Start with a similar version of the table you have created above, with enough co... | Firstly, I have to admit I like the city you chose in your example. I don't see why you are using FakeTable in this example. Why not just write the test without FakeTable and test against the real table. There are cases where this may be a bit painful. i.e. if you have a table with many required fields, but in truth th... | How to apply an index to a faked table in tSQLt | [
"",
"sql",
"sql-server",
"unit-testing",
"tsqlt",
""
] |
I have the following line in a .sql file from a mysql db:
```
ALTER TABLE lcr_gw ALTER COLUMN ip_addr TYPE VARCHAR(50) DEFAULT NULL;
```
I would like to convert it into syntax that postgresql would understand. In my personal tests, I was only able to get it to work by breaking it down into two separate statements, ... | The statement you posted is **not valid syntax at all**:
[SQL Fiddle](http://sqlfiddle.com/#!9/d610d)
To change the type in MySQL, you would use `CHANGE` or `MODIFY`.
To change the default you would use `DROP DEFAULT` or `SET DEFAULT NULL`.
**If** the intention was to change the type and reset the column default:... | [The PostgreSQL ALTER TABLE syntax diagram](http://www.postgresql.org/docs/9.3/static/sql-altertable.html) doesn't show any way to combine changing a data type and changing a default value in a single SQL statement. You can't simply omit `set default null` in the general case. For example,
```
create table test (
co... | converting mysql scripts to postgresql script | [
"",
"mysql",
"sql",
"postgresql",
""
] |
Can i use **WHERE** clause inside a **CASE** statement as given below?
**CASE WHEN A=1 THEN B WHERE C=0 ELSE A END** | In your case try this
```
CASE WHEN (A=1 AND C=0) THEN B ELSE A END AS Field_Name
``` | You can simply write
```
CASE WHEN A=1 AND C=0 THEN B ELSE A END;
``` | WHERE clause inside CASE statement | [
"",
"mysql",
"sql",
""
] |
Hello how would i be able to get the AVG of the Minimum time across records?
Meaning, I have these records:
```
Id Date Time Amount
1 7/1/14 9:00am 5.00
2 7/1/14 8:45am 6.00
3 7/1/14 9:30am 7.00
4 7/2/14 8:30am 4.50
5 7/2/14 9:15am 5.50
6 7/2/14 7:45am 4.75
```
now what i need i... | To get the average, convert the time to seconds, compute the average and convert it back to a time.
```
SELECT Id, Date, SEC_TO_TIME(AVG(sec))
FROM (SELECT Id, Date, MIN(TIME_TO_SEC(Time)) AS sec
FROM YOUR_TABLE
GROUP BY Id, Date) AS TABLE1
GROUP BY Id, Date;
``` | You can try somthing like this:-
```
SELECT Id, Date, AVG(Time)
FROM (SELECT Id, Date, MIN(Time) AS Time
FROM YOUR_TABLE
GROUP BY Id, Date) AS TABLE1
GROUP BY Id, Date;
```
This might be helpful to you. | Average Time over a period of time in a SQL Query | [
"",
"sql",
"time",
"average",
"min",
""
] |
I have two tables `item` and `status`.
`item` is a table like this:
```
id date status_id
1 10-02-2013 1
2 11-02-2013 1
3 11-03-2013 2
... ... ...
```
`status` is a table like this:
```
id status_name
1 first
2 second
3 three
... | You can do this with a `cross join` and then `left outer join`:
```
select m.month, s.status, coalesce(i.cnt, 0) as cnt
from (select distinct strftime('%m', date) as month from item) m cross join
(select id, status from status) s left outer join
(select strftime('%m', date) as month, status_id, count(*) as c... | The table with the non-matching values you want anyway must be on the left side of the LEFT JOIN.
This means you need `item LEFT JOIN status` in the inner query.
(The outer query does not need an outer join.) | How to get 0 in COUNT from different months and status? | [
"",
"sql",
"sqlite",
"count",
"left-join",
"web2py",
""
] |
I have a problem with a query that take too much time to execute. The query is:
```
SELECT id, name
FROM user
WHERE id IN ( SELECT DISTINCT ( user_id )
FROM `webchat`
WHERE closed = 0 )
```
**webchat.closed** and **user.id** are indexs. The query takes 6 seconds to complete.
B... | Try this way:
```
SELECT DISTINCT user.id, user.name
FROM user INNER JOIN `webchat` on user.id = `webchat`.user_id
WHERE `webchat`.closed = 0
``` | This is your query:
```
SELECT u.id, u.name
FROM user u
WHERE u.id IN ( SELECT DISTINCT ( user_id ) FROM webchat WHERE closed = 0 )
```
First, the `distinct` is redundant in the subquery. Second, many databases handle `exists` better than `in`. Try this:
```
SELECT u.id, u.name
FROM user u
WHERE EXISTS (select 1 fro... | SQL query takes too much time to execute | [
"",
"sql",
""
] |
I have a table contains all the name with different class, like this:
```
Name Class
Jack A
Nick B
Simon C
David B
Linda B
Alice C
```
Right now I want to get a table that with class A, B , C as columns, which contains the names inside their respect class:
```
A----------B----------C
Jack-----... | Here is a method that uses aggregation. It is probably the easiest method:
```
select max(case when class = 'a' then name end) as a,
max(case when class = 'b' then name end) as b,
max(case when class = 'c' then name end) as c
from (select name, class, row_number() over (partition by class order by (selec... | The data you're asking for isn't really very relational, and in those cases you'll usually get better results from doing the work in your client application. But as that's often not possible:
```
SELECT A.Name as A, B.Name as B, C.Name AS C
FROM
(select Name, row_number over (order by name) as ordinal from table wh... | Select Columns each with specific where condition in SQL | [
"",
"sql",
"sql-server",
""
] |
I'm trying to do a sorting using the following query:
```
SELECT * FROM client
ORDER BY
CASE $desired_colum_to_order
WHEN 'id' then `id`
WHEN 'name' then `name`
ELSE `id`
END
ASC
```
The problem is that this query is ordering ID as a string column, but it is a **Integer Primary Key**.
The results become i... | **Q: Could someone explain me why is MySQL ordering like this?**
MySQL is "ordering" the rows based on the *result* of the *expression* in the ORDER BY clause.
You've supplied a `CASE` expression in the ORDER BY clause. And that expression returns a single datatype. In this case, it appears that the expression is ret... | You can split the `order by` into different conditions:
```
SELECT *
FROM client
ORDER BY (CASE WHEN $desired_colum_to_order = 'id' then id END) ASC,
(CASE WHEN $desired_colum_to_order = 'name' then name END) ASC,
id ASC
```
This works because the `case` statements that do not match all return `NUL... | Sorting results using "ORDER BY CASE" not using primary index | [
"",
"mysql",
"sql",
"innodb",
""
] |
I am trying to get count of results found. Individually those two queries works fine, no trouble there.
But when I try to get result combined (I've used `UNION`). I get the result right but result from the second table appends to the result set.
## For Example
**The result from table one:**
When I use simple querie... | Finally had to drop the `UNION` and use `JOIN` instead. Here is the final query.
```
SELECT $leads_table.date date,
COUNT($leads_table.type) total,
SUM($leads_table.type='email') emails,
SUM($leads_table.type='call') calls,
SUM($leads_tabl... | First of all - u don't need to make sum, if u know the result. Just replace:
```
SUM('') no_answer,
SUM('') voicemail
```
with
```
0 no_answer,
0 voicemail
```
secondary - you perform a group by in 2 separate queries, and in order to get the full result u should perform it together.
therefore your combined query s... | Combine Result From Two Tables and Distinct By Date/Hour | [
"",
"mysql",
"sql",
""
] |
I have to send the report to management every morning . For that i have create schedule in Sql Server agent with following code.
```
EXEC msdb.dbo.sp_send_dbmail
@recipients='bishnu.bhandari@gmail.com',
@body='Dear sir, <Br>Please find the attachment. <P>Regards<Br> <Br>IT Department',
@subject ='TOURISM-GL( Auto By ... | Could you try,
```
declare @pathname varchar(200) = 'C:\PUMORI_NEW\**001_TOURISMGL_(,' + REPLACE(CONVERT(VARCHAR(10),GETDATE(),101),'/', '') + ', )_(SOD).TXT**';
EXEC msdb.dbo.sp_send_dbmail
@recipients='bishnu.bhandari@gmail.com',
@body='Dear sir, <Br>Please find the attachment. <P>Regards<Br> <Br>IT Department',
@... | Does it have to be inside of SQL Server? I do it with a batch file using BLAT (or Postie) with Windows Task Scheduler and SQLCMD (OSQL works too) and works just fine..
```
@ECHO OFF
@Rem -----------------------------------------------
@ECHO Procedure to e-mail daily Row Counts
C:
cd\reports
@ECHO Running database que... | Send a Mail from SQL server with attachment ( Attachment to be formed dynamically) | [
"",
"sql",
"sql-server",
""
] |
I have a `DateTime` column named `EXP_Date` which contains date like this :
```
2014-07-13 00:00:00.000
```
I want to compare them, like this query :
```
SELECT COUNT(*)
FROM DB
WHERE ('2014-07-15' - EXP_DATE) > 1
```
I expect to see the number of customers who have their services expired for over a month.
I know... | You can use [DATEADD](http://msdn.microsoft.com/en-us/library/ms186819.aspx)
```
SELECT COUNT(*)
FROM DB
where EXP_DATE < DATEADD(month, -1, GETDATE())
``` | Another way using **DATEDIFF**
---
```
SET DATEFORMAT DMY --I like to use "dateformat"
SELECT COUNT(*)
FROM DB
WHERE (DATEDIFF(DAY,@EXP_DATE,GETDATE())) >= 30 --Remember, instead "Day" you can use week, month, year, etc
```
**Syntax**: DATEDIFF ( datepart , startdate , enddate )
*Depart*: year, quarter, month, da... | Comparing dates in SQL Server | [
"",
"sql",
"sql-server",
"date",
"sql-server-2008-r2",
""
] |
How can I return `datetime` constant with `datetime` type in SQL Server?
The following code returns string type:
```
select '20010528 08:47:00.000' as DateField
``` | ```
select convert(datetime,'20010528 08:47:00.000')as DateField
or
select cast('20010528 08:47:00.000' as datetime)as DateField
``` | You may try like this:
```
select cast('20010528 08:47:00.000'as DateTime) as DateField
``` | How can I return datetime constant with datetime type in SQL Server? | [
"",
"sql",
"sql-server",
"datetime",
"constants",
""
] |
I am using MS SQL.
I have the following tables:
```
table A:
id1 data1
8234 ko
2 po
333 koo
40 woo
table B:
id2 data2
123 meow
654 frrr
table C:
id3 data3
10 a
20 b
30 c
40 d
50 ... | Try something like this:
```
SELECT *
FROM A
FULL OUTER JOIN B ON 1 = 1
FULL OUTER JOIN C ON 1 = 1
``` | Create an index using `row_number` to use for your full join
```
select * from (
select
row_number() over (order by id1 asc) rn,
id1, data1
from ta
) t1
full join (
select
row_number() over (order by id2 asc) rn,
id2, data2
from tb
) t2 on t1.rn = t2.rn
full join (... | SQL full join without any conditions | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I wrote this sql query:
```
select first_name, salary
from employees
where salary in( select distinct top(10) salary from employees order by salary disc );
```
When I ran it, I got this error:
SQL Error: ORA-00907: missing right parenthesis
00907. 00000 - "missing right parenthesis"
What could have caused the er... | Top-N query is typically performed this way in Oracle:
```
select * from (
select first_name, salary
from employees order by salary desc
) where rownum <= 10
```
This one gets you top 10 salaries. | I think the problem lies in the use of `top` which is SQL Server and not Oracle.
Use `rank` instead to get the salary in the decent order and get the first 10 of them:
```
select v.first_name, v.salary
from ( select first_name, salary, rank() over (order by salary desc) r from employees) v
where v.r <= 10
``` | Select top 10 salary from employees table | [
"",
"sql",
"oracle",
""
] |
Theres a question on an exercise which asks me to write an SQL statement to show the SKU, SKU\_Description, WarehouseID for all items stored in a warehouse managed by ‘Lucille Smith’. I have to use a join, but not use the JOIN ON syntax.
I came up with:
```
select sku, sku_description, warehouseid
from invento... | You can use the JOIN..USING syntax, as below:
**EDIT**:
Changed the manager name to Title Case
```
select sku, sku_description, warehouseid
from inventory i join warehouse w
using (warehouseid)
where manager = 'Lucille Smith';
```
**Reference**:
[JOINS IN ORACLE on DATAWAREHOUSE CONCEPTS blog](http://d... | ORA-00918 tells you that ORACLE can't decide what column to select because both tables have columns with the same name.
To address that you need to use aliases like this:
```
select alias1.common_column, alias2.common_column
select table1 alias1, table2 alias2
```
If you are not allowed to use JOIN ON, you maybe can... | Trouble quering a join in oracle sql | [
"",
"sql",
"oracle",
"join",
""
] |
Using SQL Server 2008 R2, I have a view, vwBASECustomerTransactions, with a list of transactions, which sum the aggregate data for each transaction type for each day:
```
Create View vwBASECustomerTransactions AS
Select CustomerID, 0 as TransType, Sum(Amount) as TransAmount, Cast(ChargeDate as Date) as TransDate
from ... | You can try this one to see if it runs any better that what you are seeing. After I finally figured out what it was exactly you were trying to do it is pretty much similar to your version :( The Union in the first subquery is going to basically select distinct values which will slow things down.
```
SELECT DistinctDay... | This is too long for a comment.
Unfortunately, SQL Server 2008 doesn't directly support cumulative sum. I suspect, though, that there might be more efficient ways to get what you want. SQL Server 2012 *does* support cumulative sum.
I think the best approach would be to use a temporary table rather than a view. On the... | SQL Server Find highest balance from transactions | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
As part of a stress tests I'm doing I'm trying to figure out if there is an SQL query (quite specifically SQL Server query) that will max all CPUs usage to 100% or close enough.
Suggestions anyone? | ```
SELECT SUM(CONVERT(BIGINT, o1.object_id) + CONVERT(BIGINT, o2.object_id) + CONVERT(BIGINT, o3.object_id) + CONVERT(BIGINT, o4.object_id))
FROM sys.objects o1
CROSS JOIN sys.objects o2
CROSS JOIN sys.objects o3
CROSS JOIN sys.objects o4
```
Here's a parallel version:
```
USE master
SELECT MyInt = CONVERT(BIGINT, ... | I've talked at length in [How to analyse SQL Server performance](http://rusanu.com/2014/02/24/how-to-analyse-sql-server-performance/) about why practically your query never 'executes': is always *waiting* on something (IO, locks).
To create a workload that drives 100% CPU, even on one core, is no small feat. You need ... | Trying to create an SQL Query that will max all CPUs to 100% | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"cpu-usage",
""
] |
I have a column of times and want to create a second column to show which 5 minute interval on a 24 hr clock they fall into. For example
```
15:19:52 becomes 15:15:00
15:20:11 becomes 15:20:00
``` | You can do the following. It builds the time
```
SELECT TIMEFROMPARTS(
DATEPART(HOUR, yourTimeField),
DATEPART(MINUTE, yourTimeField) / 5 * 5, 0,
0,
0)
FROM yourTable
```
[Link to SQL Fiddle Example](http://sqlfiddle.com/#!6/34f73/4) | There is a thread I found that may help you begin getting started with this.
[T-SQL: Round to nearest 15 minute interval](https://stackoverflow.com/questions/830792/t-sql-round-to-nearest-15-minute-interval)
However, all the examples here only seem to round up, so you'd need to subtract 5 from the result to get what ... | Grouping a time field into 5 minute periods in SQL server | [
"",
"sql",
"sql-server-2012",
""
] |
First of all this is kind of a duplicate to:
[GROUP BY having MAX date](https://stackoverflow.com/questions/18221999/group-by-having-max-date/18222124?noredirect=1#comment38513130_18222124)
I am posting the question because the accepted answer doesn't work for me and I have no idea why. My problem:
I want to select th... | As I understand the sintaxis from MySQL when you put USING for an Inner Join the columns need to be named the same in both tables. There is no column named maxdate on the content table so the error jumps. You may be able to try (if I understand things correctly)
```
SELECT func_id,checksum
FROM Content cnt
INNER JOIN... | Use an `on` clause instead of `using`:
```
SELECT func_id,checksum
FROM Content cnt INNER JOIN
(SELECT func_id, MAX(timestamp) AS maxtimestamp
FROM Content
GROUP BY func_id
) m
on m.func_id = cnt.func_id and m.maxtimestamp = cnt.timestamp;
``` | Group by max(time) mysql | [
"",
"mysql",
"sql",
""
] |
I have 2 tables which look like:
The `money` table looks like the following:
```
id type cash
1 54 3.23
2 293 1.12
3 181 4.00
```
The `plus` table looks like the following:
```
id money_id bonus
1 3 0.50
2 2 0.10
```
What I basically want is to select ALL data fro... | *1. Assuming you can have more than one bonus per money id :*
You can use an alias in an having clause (with mysql), after having grouped the values from money table
```
select mo.id, mo.type, mo.cash + sum(coalesce(p.bonus, 0)) as cash_full
from money mo
left join plus p on p.money_id = mo.id
group by mo.id, mo.typ... | A simple LEFT JOIN will do it:-
```
SELECT a.id, a.type, a.cash + IFNULL(SUM(b.bonus), 0) AS cash_bonus
FROM money a
LEFT OUTER JOIN plus b
ON a.id = b.money_id
GROUP BY a.id, a.type
HAVING cash_bonus > 1.50
```
Note that this is a bit strange as it has a non aggregate field that isn't in the GROUP BY clause. This s... | How to select a sub-query with MySQL using the WHERE part? | [
"",
"mysql",
"sql",
""
] |
Say I have a table with a `created`, `uploaded`, `processed` and `archived` columns, all of which accept a date. However, I want it so the fields have to be updated in chronological order and you can't skip a step, but the trailing steps don't have to be set until they're ready (i.e., created <= uploaded <= processed <... | In the end, I went for my own solution:
```
create table batch (
id number primary key,
created date default sysdate not null,
uploaded date,
processed date,
archived date,
check (uploaded is null or uploaded >= created),
check (processed is null or (uploaded is not null and processed >= u... | I think your design is sound. I would split the checks for chronological order and the NULL checks, but this is only a question of style, not logic.
```
create table batch (
id number primary key,
created date default sysdate not null,
uploaded date,
processed date,
archived date,
CHECK (crea... | Sequential constraints on table columns | [
"",
"sql",
"oracle",
"constraints",
""
] |
I have a model that defines mutually recursive tables:
```
Answer
questionId QuestionId
text
Question
text
correct AnswerId
```
What do I need to do to actually insert a question? I need to know what the correct answer is first. But to insert an answer, I need to know what question it answers.
I'm running P... | If you enter question and answer in a **single statement** with a [data-modifying CTE](https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-MODIFYING), you do not even need a `DEFERRABLE` FK constraints. Not to speak of actually making (or `SET`ting) them `DEFERRED` - which would be a lot more expensi... | I went looking around after seeing the DDL. Consider a function for your call to insert a question with correct answer, and one to add (false) answers to a given question. The structure of the first function allows the application to pick up the anonymous returned record for the questionID, and use it for subsequent ca... | How to deal with mutually dependent inserts | [
"",
"sql",
"postgresql",
"database-design",
"foreign-keys",
"referential-integrity",
""
] |
I'm Using **Amazon Redshift**. I need to get the **MAX** Date in the column by Month wise. The Example is as below.
There are 5 tables:
```
vendor
vendor_pkg
vendor_pkg_category
vendor_load
vendor_load_status
vendor V
vendor_id vendor_name
-----------------------
1 L&T
2 Reuters
3 ... | I Found the Answer for my Question.
```
SELECT DISTINCT v.vendor_name AS vendor,
vpc.category_name AS V_Type,
vp.vendor_pkg_name AS Package_name,
vl.eval_date AS C_Date,
vls.load_status_name AS Status
FROM ces_idw.vendor v,
ces_idw.vendor_pkg_category vpc,
ces_idw.vendor_load vl,
... | As per your sample data i wrote query this gives you mentioned result set
```
DECLARE @exp table (ID INT,Name VARCHAR(10))
INSERT INTO @exp (ID,Name) VALUES (1,'PRICE')
INSERT INTO @exp (ID,Name) VALUES (2,'STOCK')
INSERT INTO @exp (ID,Name) VALUES (3,'INCOME')
INSERT INTO @exp (ID,Name) VALUES (4,'LOAD')
INSERT INTO ... | Get max values in PostgreSQL 8.0 | [
"",
"sql",
"postgresql",
"join",
"date-range",
"amazon-redshift",
""
] |
I need a support of yours, today i got a scenario which i need to do that.
the scenario is email which consists with username and id, needs to split and insert into table in two different columns i.e user id, username.
`ex: ABC123@xyz.com, AAACC2356@mnc.com`
`ABC to be insert in table under username column and 123 t... | You can try this:
```
DECLARE @Email VARCHAR(100)= 'sample12312@test.com'
SET @Email = STUFF(@Email,CHARINDEX('@',@Email),LEN(@Email), '')
SELECT SUBSTRING(@Email, 1, PATINDEX('%[0-9]%',@Email)-1) AS Username,
SUBSTRING(@Email,PATINDEX('%[0-9]%',@Email), LEN(@Email)) AS UserID
```
OR
```
SELECT SUBSTRING(... | ```
Declare @X varchar(100)
Select @X= 'AAACC2356@mnc.com'
Select @X= SubString(@X,PATINDEX('%[0-9]%',@X),Len(@X))
Select @X= SubString(@X,0,PATINDEX('%[^0-9]%',@X))
Select @X
Declare @Y varchar(100)
Select @Y = 'AAACC2356@mnc.com'
Select @Y= SubString(@Y,PATINDEX('%[A-Z... | Extracting usernames and userid from E-mail IDs using Ms-SQL | [
"",
"sql",
"sql-server",
""
] |
I have a problem about storing multiple categorical data. One category can have any size of cascade depth. I think it is not good idea to create more tables with relationships. What is the best way of storing this kind of categorical data.
```
ex categories:
-MainCategory1
-subcategory1
-subcategory1... | You need to define parent child structure
```
CREATE TABLE CATEGORIES (ID INT, PARENT_ID INT, NAME VARCHAR)
```
then you select categories that have no `PARENT_ID`
```
SELECT * FROM CATEGORIES WHERE PARENT_ID IS NULL
```
they are masters and then on each layer you select
```
SELECT C.* FROM CATEGORIES C
INNER JOI... | One common practice would be to create a single table where each category has an id, a name and a parent id (with top categories having parent id of `null`):
```
CREATE TABLE categories (
id NUMERIC PRIMARY KEY,
name VARCHAR(100),
parent_id NUMERIC FOREIGN KEY REFERENCES categories(Id)
)
```
Some of yo... | How to store cascade categories in DB | [
"",
"sql",
"sql-server",
"database",
"stored-procedures",
"categories",
""
] |
I am working on a file loader program.
The purpose of this program is to take an input file, do some conversions on its data and then upload the data into the database of Oracle.
The problem that I am facing is that I need to optimize the insertion of very large input data on Oracle.
I am uploading data into the tab... | I know others have mentioned this and you don't want to hear it but use [SQL\*Loader](http://docs.oracle.com/cd/E11882_01/server.112/e40540/cncptdba.htm#CNCPT1282) or [external tables](http://docs.oracle.com/cd/E11882_01/server.112/e25494/tables.htm#ADMIN12896). My average load time for tables of approximately the same... | If you have a text file you should try [SQL LOADER](http://docs.oracle.com/cd/B19306_01/server.102/b14215/ldr_concepts.htm) with direct path. It is really fast and it is designed for this kind of massive data loads. Have a look at this [options](http://www.dba-oracle.com/t_optimize_sql_loader_sqlldr_performance.htm) th... | INSERT of 10 million queries under 10 minutes in Oracle? | [
"",
"sql",
"database",
"oracle",
"oracle-call-interface",
"bulk-load",
""
] |
I have a query that is pulling out submissions from one table and then the count of votes from another table. I then want to order the records based on the total votes which is gathered from a sub query.
How can I order this table by totalVotes which is gathered in the subquery?
```
SELECT A.[submissionID],
A.... | you may need to order it before the FOR XML:
```
SELECT(
SELECT A.[submissionID],
A.[entryID],
E.[subEmpID],
E.[nomineeEmpID],
CONVERT (VARCHAR (10), E.[submissionDate], 101) AS submissionDate,
E.[situation],
E.[task],
E.[action],
E.[result],
E.[timestamp]... | ```
SELECT * FROM
(
SELECT A.[submissionID],
A.[entryID],
E.[subEmpID],
E.[nomineeEmpID],
CONVERT (VARCHAR (10), E.[submissionDate], 101) AS submissionDate,
E.[situation],
E.[task],
E.[action],
E.[result],
E.[timestamp],
E.[statusID],
E.[appro... | TSQL Order results by value of subselect | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I'd like to get value by the following SQL using Eloquent ORM.
**- SQL**
```
SELECT COUNT(*) FROM
(SELECT * FROM abc GROUP BY col1) AS a;
```
Then I considered the following.
**- Code**
```
$sql = Abc::from('abc AS a')->groupBy('col1')->toSql();
$num = Abc::from(\DB::raw($sql))->count();
print $num;
```
I'm... | In addition to @delmadord's answer and your comments:
Currently there is no method to create subquery in `FROM` clause, so you need to manually use raw statement, then, if necessary, you will merge all the bindings:
```
$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance
$count = DB::table( DB::raw("({$... | Laravel v5.6.12 (2018-03-14) added `fromSub()` and `fromRaw()` methods to query builder [(#23476)](https://github.com/laravel/framework/pull/23476).
The accepted answer is correct but can be simplified into:
```
DB::query()->fromSub(function ($query) {
$query->from('abc')->groupBy('col1');
}, 'a')->count();
```
... | How to select from subquery using Laravel Query Builder? | [
"",
"sql",
"laravel",
"laravel-4",
"eloquent",
"query-builder",
""
] |
I have this SQL Query:
```
select prefix, code, stat, complete, COUNT(*) as Count
from table
group by prefix, code, stat, complete
order by prefix, code, stat, complete
```
The column 'prefix' is an alphanumeric value (0-9a-zA-z).
What I want is to make it so that if the value of prefix is a number, to make the numbe... | ```
case when prefix like '%[0-9]%' then '0' else prefix end
```
You obviously also need this as the expression in the `GROUP BY`:
```
select
NewPrefix = case when prefix like '%[0-9]%' then '0' else prefix end,
code,
stat,
complete,
COUNT(*) as Count
from table
group by
case when prefix... | Try this :
```
select case when prefix not like '%[^0-9]%' then prefix else '0' end as prefix, code, stat, complete, COUNT(*) as Count
from table
group by case when prefix not like '%[^0-9]%' then prefix else '0' end, code, stat, complete
order by prefix, code, stat, complete
```
[Check This. Looks similar "ISNUMERIC... | GROUP BY multiple values in same column | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table 1 (`MID, SSN, ...`) `MID` is primary key and table 2 (`ID, SSN, StateCode..`) where `ID` and `SSN` make up the primary key. I'm trying to display all columns from table 1 along with `StateCode` from table 2 matching it against `SSN`. Tbl 1 has 50 rows and some have same `SSN` values.
If no `SSN` match i... | I'd suggest reading on [cartesian product](http://en.wikipedia.org/wiki/Cartesian_product).
If you have 50 rows in the first table and 70 in the second that makes 3500 rows. The join condition `tbl1.SSN = tbl2.SSN` will filter out rows but you may well end up with more than 50 rows.
Back to your problem you can see w... | Try,
Your both Table have one more primary key is there So just try ID column to match
```
Select tbl1.MID,tbl1.SSN, tbl2.StateCode
from tbl1
left outer join tbl2
on tbl1.MID= tbl2.ID
Group by tbl1.MID,tbl1.SSN, tbl2.StateCode
``` | Left outer Join query returns duplicates in SQL Server | [
"",
"sql",
"duplicates",
"left-join",
""
] |
I want to combine these two statements in to one:
```
SELECT o.SITE AS "Site",
COUNT(o.ORDER_NO) AS "No. Orders",
FROM ORDERS o
WHERE o.DATE_CREATED BETWEEN '01-JUL-13' AND '1-JUL-14'
GROUP BY o.SITE;
```
and
```
SELECT o.SITE AS "Site",
COUNT(oi.LINE_CODE) ... | You could use a sub select so that it functions the same as in your first query.
```
SELECT o.SITE AS "Site",
COUNT(oi.LINE_CODE) AS "No. Order Lines",
COUNT(DISTINCT oi.LINE_CODE) AS "No. Order Lines (UNIQUE)",
(SELECT COUNT(o2.ORDER_NO)
FROM ORDERS o2 ... | you want something like that?
```
select o.site as "Site",
count(oi.line_code) as "No. Order Lines",
count(distinct oi.line_code) as "No. Order Lines (UNIQUE)",
count(o.order_no) as "No. Orders"
from order_items oi, orders o
where oi.order_no = o.order_no
and oi.order_type = o.order_type
and o... | Selecting items from multiple tables with different WHERE statement | [
"",
"sql",
""
] |
I have three tables in my database.
Table one effectively contains two fields:
```
|Datetime| |Set|
```
Table two is a lookup table which matches a number of parts of a set to a set number:
```
|Set| |Part1| |Part2| |Part3| |Part4|
```
I want table 3 to have a record for each part in a set for a particular datetim... | Perhaps something like...
```
Insert Into table3 (
Select datetime, set + '_' + Part1
FROM table1
INNER JOIN table2
on T1.Set=T2.Set
and Part1 is not null
UNION
Select datetime, set + '_' + Part2
FROM table1
INNER JOIN table2
on T1.Set=T2.Set
and Part2 is not null
UNION
Select datetime, set + '_' + Part3
FR... | The "canonical" way to do this in SQL Server is to use `union all`:
```
select t1.datetime, t2.part
from ((select set, Part1 as part from table2) union all
(select set, Part2 from table2) union all
(select set, Part3 from table2) union all
(select set, Part4 from table2)
) t join
table1 t1
... | SQL to look up table and make one record per field | [
"",
"sql",
"sql-server",
"database",
""
] |
I have a table with columns First Name and Last Name and an ID which is the PK. My WHERE condition will be a search operation upon the FullName and not separately.
SELECT:
```
select ID, FirstName + ' ' + LastName as FullName
from tbl_Employee
```
What I want:
```
select ID, FirstName + ' ' + LastName as FullName ... | You can structure the query a couple of different ways. One, include the concatenataion in the `where` clause:
```
select
e.ID,
e.FirstName + ' ' + e.LastName as FullName
from tbl_Employee as e
where e.FirstName + ' ' + e.LastName like '%' + @searchText + '%';
```
Two, use a sub-select as @lajja has shown.
... | You can do this
```
select ID, FirstName + ' ' + LastName as FullName
from tbl_Employee
where (FirstName + ' ' + LastName) like '''%' + @searchText + '%'''
``` | How to refer a custom column in the same SQL query | [
"",
"sql",
"sql-server-2008",
""
] |
This very simple query I am trying to execute in SQL Server Management Studio. But it gives error:
```
CREATE TABLE `contact` (
`contact_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`address` varchar(45) NOT NULL,
`telephone` varchar(45) NOT NULL,
PRIMARY ... | The backtick (`` ` ``) character is only used for MySql. It's not standard. Sql Server is a completely different animal. You need to use square-brackets (`[` and `]` -- also not standard) to enclose table and column names with Sql Server. Sql Server also supports double quotes (`"`), which are part of the SQL Standard,... | in tsql
```
CREATE TABLE contact (
contact_id int identity(0,25) NOT NULL,
name nvarchar(45) NOT NULL,
email nvarchar(45) NOT NULL,
address nvarchar(45) NOT NULL,
telephone nvarchar(45) NOT NULL
CONSTRAINT contact_PK PRIMARY KEY (contact_id)
)
```
You can't specify engine.
identity(0,25) means initial v... | Execute query in SQL Server Management Studio | [
"",
"sql",
"sql-server",
"ssms",
""
] |
I want to "group by" ver two unicode fields (keyword\_text and keyword\_match\_type) and extract all columns and all rows for the groups which have more than two elements.
For example one row is:
```
keyword_text | keyword_norm | keyword_GAD_id| keyword_account | keyword_MCC_id | keyword_campaign | keyword_campaign_... | You can use `EXISTS` for this type of query - so no `COUNT` at all (!), just a check that at least another row exists with same campaign\_status and ad\_group\_status. The check on the primary keys is to ensure just that, that it is another row:
```
WITH cte AS
( SELECT *
FROM adword_keywords
WHERE (keywo... | When you `GROUP BY` some fields, you're doing two important things:
1. You're saying that you want rows where combinations of those fields are distinct.
2. You're saying that all the *other* fields you use, you're going to aggregate.
That "other" might be a problem here. If you're grouping by a field, you can't decen... | Postgres group by and extract groups with more than one element | [
"",
"sql",
"postgresql",
""
] |
My table name is `emails`.
My table structures looks like:

I want to remove all of the duplicated emails. I tried this query:
```
DELETE FROM emails WHERE email NOT IN (SELECT MIN(email)
FROM emails GROUP BY email)
```
But with no result. Can... | The query that you are looking for would use `id`, not `email`:
```
DELETE FROM emails
WHERE id NOT IN (SELECT MIN(id) FROM emails GROUP BY email) ;
```
EDIT:
You are using MySQL. You can get around this with the subquery hack:
```
DELETE FROM emails
WHERE id NOT IN (select minid from (SELECT MIN(id) as min... | Try this instead
--CREATE a Temporary table
```
create table IDsToRemove (ID Int)
INSERT INTO IDStoRemove
SELECT MIN(id) _
FROM emails GROUP BY email
DELETE FROM emails WHERE id NOT IN (SELECT id from IDStoRemove)
```
I don't know the exact mySQL syntax, but should give you the idea | How do I remove duplicates row in SQL? | [
"",
"mysql",
"sql",
"duplicates",
""
] |
I'm trying the following query:
```
SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5;
```
(The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.)
I get the error:
```
ERROR: operator does not exist: jsonb ... | There are two operations to get value from `JSON`. The first one `->` will return `JSON`. The second one `->>` will return text.
Details: [JSON Functions and Operators](http://www.postgresql.org/docs/current/static/functions-json.html)
Try
```
SELECT (json_data->'position'->>'lat')::float + 1.0 AS lat
FROM updates
L... | AFAIK there's no json->float casting in Postgres, so you could try an explicit `(json_data->'position'->'lat')::text::float` cast | How to convert PostgreSQL 9.4's jsonb type to float | [
"",
"sql",
"postgresql",
"casting",
"jsonb",
"postgresql-9.4",
""
] |
I'm training with `SQLite` and i'm trying to achieve the same result as the search result implemented in USDA.
In [USDA food list search](http://ndb.nal.usda.gov/ndb/foods) if I search for "chicken breast cooked roasted" the search results 56 results.
I'm can't figure out the pattern. Using the same database as they, ... | You can investigate the number of matches to the keywords using this query:
```
SELECT ((FOODDES LIKE '%chicken%') +
(FOODDES LIKE '%breast%') +
(FOODDES LIKE '%cooked%')
(FOODDES LIKE '%roasted%')
) as NumMatches, count(*), min(fooddes), max(fooddes)
FROM FOODDATA
GROUP BY (FOODDES LIKE... | Try something like
```
select
(FOODDES LIKE '%chicken%') + (FOODDES LIKE '%breast%') + (FOODDES LIKE '%cooked%') + (FOODDES LIKE '%roasted%') As matches ,
FOODDES
from
(
SELECT FOODDES
FROM FOODDATA
WHERE FOODDES LIKE '%chicken%' or FOODDES LIKE '%breast%' or FOODDES LIKE '%cooked%' or FOODDES... | Understanding SQLite query | [
"",
"sql",
"sqlite",
""
] |
I have 2 separate tables in MySQL (I'm using Sequel Pro on a Mac) with the exact same column names. Is there a function to join these tables and create one table with the same headers?
Example of what I'm trying to do:
```
Table 1
a b c
1 2 4
3 3 1
Table 2
a b c
3 2 1
8 4 2
Output
a b ... | ```
create table table_3 as
select * from table_1
union
select * from table_2
```
If you don't want to keep duplicates.
UNION ALL if you do want to keep duplicates. | ```
CREATE TABLE new_table_name AS
select *
from table1
cross join table2
```
or
```
CREATE TABLE new_table_name AS
select * from table1
union all
select * from table2
``` | MySQL - combine 2 tables | [
"",
"mysql",
"sql",
""
] |
I am trying to write a dynamic T-SQL query and running into an error.
I have removed everything except a single var and I still get the error when trying to run the query.
```
ALTER PROCEDURE [dbo].[empowermentFetchSubmissions2]
@category INT=NULL
AS
DECLARE @sSQL AS NVARCHAR (3000),
@Where AS NVARCHAR (1000) = '';
... | I have modified your code to the point where I think it will work. There were 3 problems I found by commenting out your execute line and putting a `print @ssql` before it. Then executed the stored procedure. First problem was the quotes. I changed them to single quotes. Next a new line for the `WHERE` where it was on t... | You need to change the double quotes to two single quotes:
```
B.[FirstName] + '' '' + B.[LastName] AS nomineeName,
C.[FirstName] + '' '' + C.[LastName] AS submitName,
```
EDIT:
You also need a space in front of WHERE on this line:
```
SET @sSQL = @sSQL + ' WHERE ' + RIGHT(@Where, LEN(@Where) - 3);
``` | Dynamic TSQL Query | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have a table like this:
**ACTUAL TABLE**
```
ID | Type | Number
----------+----------
1 | x | 2000
2 | y | 4500
3 | y | 4500
4 | x | 3000
5 | y | 5000
6 | x | 4000
7 | y | 7500
8 | y | 7500
```
And I want to update the `y` to be exact as the `x` before it:... | Just update based on your ID:
`UPDATE <tablename> SET <fieldname> = (SELECT <fieldname> FROM <tablename> WHERE id = 1) WHERE id = 2`
It might work. | Try Like This
`t` is tablename
`a` is type
`va` is number
```
update t join (
select curr.id, max(prior.id) prior_id
from t curr
join t prior
on prior.a = 'x'
and prior.id < curr.id
where curr.a = 'y'
group by curr.id) g
on g.id = t.id
join t... | How to update a MySQL row based on previous row? | [
"",
"mysql",
"sql",
"database",
""
] |
One of my tables have values like this..
```
Year 1
Year 9
Year 8
Year 4
Kindy [can be any word without numbers]
Pre-School [can be any word without numbers]
Year 8
Year 22
Year 15....
```
How can I sort Them in alphabetically first and then by numerically in ascending order like this..
```
Kindy
Pre-School
Year 1
... | If the column with digits always has the `Year [digits]` format, you can try this
```
SELECT YearLevel FROM student
GROUP BY YearLevel
ORDER BY
(CASE
WHEN YearLevel LIKE 'Year%'
THEN 'Year' + CONVERT(varchar,LEN(YearLevel)) + YearLevel
ELSE YearLevel
END)
```
<http://sqlfiddle.com/#... | ```
select
astring
from table1
order by
case when left(astring,5) = 'Year ' then 2
else 1 end
, case when left(astring,5) = 'Year ' then right(replace(astring,'Year ','00000000'),3)
else astring end
, astring
```
see [this sqlfiddle](http://sqlfiddle.com/#!3/70cae/1) | Query in sql server to sort data which has both numbers and alphabets | [
"",
"sql",
"sql-server",
""
] |
Is there a simple PostgreSQL or even SQL way of listing empty/not empty tables?
P.S.:
I'm analyzing a database containing hundreds of tables and would like to detect "death code".
I assume, when the table after some month is still empty, than it's not used.
**EDIT:Solved**
Thank you all!
Finally this statement seems... | Checking for the number of rows *could* give you wrong results. Assume that a table is used as a staging table: rows get inserted (e.g. from a flat file), processed and deleted. If you check the number of rows in that table you could very well believe it's never used if you don't happen to run your query while the proc... | You could use PostgreSQL's system catalogs with e.g.
```
SELECT n.nspname, c.relname
FROM pg_class c
INNER JOIN pg_namespace n ON (n.oid = c.relnamespace)
WHERE c.reltuples = 0 AND c.relkind = 'r';
```
According to the documentation, the number of rows is an estimate, though.
If your tables have columns that take th... | show all not empty tables in postgres | [
"",
"sql",
"postgresql",
""
] |
If I have a column in which strings vary in length but they ALL have a slash `\` within,
how can I SELECT to have one column display everything BEFORE the `\` and another column displaying everything AFTER the `\`?
```
name column1 column2
DB5697\DEV DB5697 DEV
```
I have seen `CHARINDEX` and `REVE... | How about the following ([**SQL Fiddle**](http://sqlfiddle.com/#!6/851ac/1/0)):
```
SELECT m.name,
LEFT(m.name, CHARINDEX('\', m.name) - 1) AS column1,
RIGHT(m.name, LEN(m.name) - CHARINDEX('\', m.name)) AS column2
FROM MyTable m
```
How to handle strings with no `\` in them ([**SQL Fiddle**](http://sql... | what about using [PARSENAME](http://msdn.microsoft.com/library/ms188006(v=sql.110).aspx) function in a tricky way?
```
USE tempdb;
GO
CREATE TABLE #names
(
id int NOT NULL PRIMARY KEY CLUSTERED
, name varchar(30) NOT NULL
);
GO
INSERT INTO #names (id, name)
VALUES
(1, 'DB5697\DEV'),
(2, 'DB5800\S... | Splitting value of a varchar column into two columns | [
"",
"sql",
"sql-server",
"t-sql",
"case",
""
] |
```
SELECT *
FROM Service
WHERE cusId='$cusId'
AND serviceType IN (1,2)
ORDER BY date DESC LIMIT 2
```
I want to have last records of services which have serviceType of 1 and 2, when I use this script with IN query, I get 2 rows of services which has serviceType of 1, but I want to have two records, which have 1 and... | ```
(select * from Service
where cusId='$cusId'
and serviceType = 1
order by date desc limit 1)
UNION
(select * from Service
where cusId='$cusId'
and serviceType = 2
order by date desc limit 1)
``` | can you try union ?
```
SELECT top 1 * FROM Service where cusId='$cusId' and serviceType = 1 order by date DESC
UNION
SELECT top 1 * FROM Service where cusId='$cusId' and serviceType = 2 order by date DESC
``` | How to get all the rows that have multiple values | [
"",
"mysql",
"sql",
""
] |
I have one table to register all my images for example clients logo, users photos and promotions images. The problem is that one promotion might have more than one image. As I use this table for other imagens besides from promotion, I can´t use a foreign key inside it. So my doubt is what to do, create a intermediate t... | if 1 image can be in many promotions and one promotion can has many images, then create relation **N:N** by 3 tables:
```
image:
imageID INT,
image YOUR_TYPE_OF_IMAGE,
...
promotion:
promotionID INT,
description VARCHAR(255),
name VARCHAR(255),
...
image_and_promotion:
imageID INT,
promotionID INT
```
You can a... | You should create an intermediate table between promotions and images | How to create a relation N:N and 1:N in the same table? | [
"",
"sql",
"database",
"relation",
""
] |
I have 2012 SQL Server stored procedure ran automatically every fifth of the month but the problem I have is supplying previous month date range e.g. I need to have clause like **...where datein between '2014-02-01' and '2014-02-28'** and next month it would change it to **...where datein between '2014-03-01' and '2014... | This should work
```
SELECT DATEADD(DAY,1,EOMONTH(GETDATE(),-2)) AS StartDate, EOMONTH(GETDATE(),-1) AS EndDate
```
To be more specific in your WHERE clause
```
WHERE @datein BETWEEN DATEADD(DAY,1,EOMONTH(GETDATE(),-2)) AND EOMONTH(GETDATE(),-1)
``` | You can use `getdate()` and some date arithmetic. Here is a relatively easy way:
```
where datein >= cast(dateadd(month, -1, getdate() - day(getdate()) + 1) as date) and
datein < cast(getdate() - day(getdate()) + 1)
```
The key idea here is to subtract the day of the month and add 1 to get the first day of the ... | how to get automatically previous month date range in SQL? | [
"",
"sql",
"sql-server",
""
] |
I have downloaded Microsoft SQL Server Management Studio 2014 Express. I have set it up and I now need to connect to the server. I think my server name has something to do with my computer name but its not working. How do I get in? | Assuming you installed SQL Server, and not just SSMS please read this:
<http://msdn.microsoft.com/en-us/library/ms143531(v=sql.120).aspx>
In all likelihood it was setup with the default instance name of \SQLExpress. So to connect, you would enter machinename\SQLExpress.
Ex: `Office-PC1\SQLExpress`
> If you specify ... | Assuming you actually installed the db server, and NOT just the management tools, you can always use "localhost" (without the quotes). Have you made sure you are using port 1433? I am not sure if that was a question during the setup. | SQL Server 2014 Express Set Up | [
"",
"sql",
"sql-server",
"installation",
"sql-server-express",
"sql-server-2014-express",
""
] |
I have tried <http://sqlzoo.net/wiki/Self_join>
> Self Join: Find the routes involving two buses that can go from Craiglockhart to Sighthill.Show the bus no. and company for the first bus, the name of the stop for the transfer,and the bus no. and company for the second bus.
My code:
```
SELECT a.num, a.company,
... | RE: the sorting 'bug', this is due to the way the application sorts. It sorts alphabetically; so 10 comes before 2, etc. [This article](https://stackoverflow.com/questions/153633/natural-sort-in-mysql) shows a way to do "natural sorting" using LENGTH().
For this particular problem, I was able to get the correct answer... | My solution to this problem:
I divided the problem into two.
> First subquery will be the table S(Start), which will get all the
> routes that start from 'Craiglockhart' Second subquery will be the
> table E(End), which will get all the routes that start from
> 'Sighthill'
Now both table S and E will have common rout... | Self join tutorial on SQLZoo | [
"",
"mysql",
"sql",
"join",
"self-join",
""
] |
I was facing a problem on how to create a calculated column based on a column which contains dates. For example, I have a column which contains dates starting from July.
The DAY needs to be calculated as described in the picture using SQL server.
So basically can a column be created based on an existing column contai... | With table, DateTable with a column Date of type Date, the following query will do what you ask.
```
SELECT
DATENAME(dw, Date) AS WeekDay
,Date
,ROW_NUMBER() OVER (ORDER BY Date) AS Day
FROM DateTable
WHERE DATEPART(dw, Date) NOT IN (1, 7)
ORDER BY Date
``` | Based on the Title and subject, I am guessing that you want to try and identify the working day number of each month.
> example:
>
> 1-Jan-14 is Wednesday so its Working day number 1
>
> 6-Jan-14 is Monday so its working day number 4 as (4-Jan-14 and 5-Jan-14 are Weekends)
Also the result should be a derived column i... | Count of weekdays in a given month | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
```
CREATE TABLE #TempTBL
(
ID INT IDENTITY(1,1),
KC1 varchar(10),
KC2 varchar(10),
KC3 varchar(10),
NC1 int,
NC2 money,
IsON bit
)
INSERT INTO #TempTBL
SELECT 'ABC','MNO','XYZ',1,1.00,1
UNION ALL
SELECT 'ABC','MNO','XYZ',1,1.00,0
UNION ALL
SELECT 'ABD','MNO','XYZ',1,1.10,1
UNION ALL... | Your `RowNum` is actually a `DENSE_RANK()`, and you can use a conditional aggregate for the counts, (either `SUM()` like below, or `COUNT()`):
```
SELECT *
,RowNum = DENSE_RANK() OVER(ORDER BY KC1,KC2,KC3)
,OnCNT = SUM(CASE WHEN IsON = 1 THEN 1 END) OVER(PARTITION BY KC1,KC2,KC3)
,OffCNT = COALESCE(S... | ```
Use [Windowing Functions][1]
SELECT *,
,DENSE_RANK() OVER(ORDER BY KC1,KC2,KC3) AS Row_Num
,COUNT(CASE IsON WHEN 1 THEN 1 END) OVER(PARTITION BY KC1,KC2,KC3) AS OnCnt
,COUNT(CASE IsON WHEN 0 THEN 1 END) OVER(PARTITION BY KC1,KC2,KC3) AS OffCnt
FROM MyTable
``` | T-SQL | Counts and ranks | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Database ::
* id subid
* 1 1
* 2 1
* 3 2
* 4 3
The id column is automatically incremented and primary
subid is any number.
I want to arrange subid in decreasing order, remove rows which consists
duplicate subid in it and get rows
Result i want ::
* id subid
* 4 3
* 3 2
* 2 1 | ```
SELECT MAX(id), subid FROM table GROUP BY subid ORDER BY subid DESC
``` | ```
select max(id), subid group by subid order by subid desc
``` | Deselect duplicates in sql | [
"",
"mysql",
"sql",
"duplicates",
""
] |
I have this SQL command that creates a table with a `GEOGRAPHY`-type column for spatial data that is meant to store a latitude/longitude pair (a point). How can I set a default value for that column? For example, a point at (0,0)?
```
CREATE TABLE [dbo].[StationLocations] (
[Id] [int] NOT NULL,
[StationId] [in... | try this:
```
CREATE TABLE #TEMP(ID INT,COL1 GEOGRAPHY DEFAULT(CONVERT(GEOGRAPHY,'POINT (0 0)')))
INSERT INTO #TEMP (ID) VALUES(1)
SELECT * FROM #TEMP
ID COL1
1 0xE6100000010C00000000000000000000000000000000
SELECT ID,CONVERT(VARCHAR,COL1) AS DEF_VALUE FROM #TEMP
ID DEF_VALUE
1 POINT (0 0)
```
In your case
``... | Not sure if this is the best method but, using [this answer](https://stackoverflow.com/a/8267910 "Update statement- Geography column - sql server") as a reference, you could define it [like this](http://sqlfiddle.com/#!3/a5b3b5/1 "Demo at SQL Fiddle"):
```
ALTER TABLE dbo.StationLocations
ADD CONSTRAINT DF_StationLoca... | How to set a point as default value for a geography column? | [
"",
"sql",
"sql-server",
"spatial",
"geography",
""
] |
In the below code i have pass multiple values with comma Separated to @i\_CustomerGroupID and one value to @i\_LocationID.In which i face a issue "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has be... | You want to use `insert . . . select`:
```
INSERT INTO CustomerGroupLocationMap(LocationID, CustomerGroupID)
SELECT @i_LocationID, t.*
FROM dbo.CSVToTable(@i_CustomerGroupID) t;
```
Your function `dbo.CSVToTable()` returns more than one value (I assume there is only one column). The correct synta... | ```
IF NOT EXISTS (SELECT TOP 1 FROM CustomerGroupLocationMap WHERE LocationID = @i_LocationID AND CustomerGroupID = @i_CustomerGroupID)
BEGIN
INSERT INTO CustomerGroupLocationMap (LocationID, CustomerGroupID) VALUES (@i_LocationID, (SELECT * FROM dbo.CSVToTable(@i_CustomerGroupID)));
END
``` | Sql Insert Error -"Subquery returned more than 1 value" | [
"",
"sql",
"sql-server",
""
] |
MS Access has generated the following query:
```
SELECT Port.portName, Auth.portID,
Region.RegionName, Region.RegionID,
Auth.authID
FROM Region
INNER JOIN (Auth INNER JOIN Port ON Auth.portID = Port.portID)
ON Region.RegionID = Port.RegionID;
```
and I want to
```
GROUP BY Region.RegionID
```
When I... | This selects the port with the greatest id per region
```
SELECT
Port.portName,
Auth.portID,
Region.RegionName,
Region.RegionID,
Auth.authID
FROM Region
INNER JOIN Port ON Region.RegionID = Port.RegionID
INNER JOIN Auth ON Auth.portID = Port.portID
INNER JOIN (
SELECT max(Port.portID) max... | Are trying to do this?:
```
SELECT Region.RegionID, Region.RegionName, Port.portName, Auth.authID
FROM Auth
INNER JOIN Port ON Port.portID = Auth.portID
INNER JOIN Region ON Region.RegionID = Port.RegionID
ORDER BY Region.RegionID
``` | SQL Group By with Inner Joins | [
"",
"sql",
""
] |
Check my table below:
```
ID Number01 Number02 Number03
-----------------------------------
1 10 20 4510
2 5 2 545
3 4 4 664
4 10 1 NULL
5 1 4 NULL
```
"Number03" field is a calculated field which is Number01 + Number02. I am us... | Since you're using SQL Server 2008, you can use a [**computed field**](http://msdn.microsoft.com/en-us/library/ms188300(v=sql.105).aspx) to generate the value from the other two fields.
If you just want to update the table without doing this, you could use the following SQL:
```
UPDATE _myTable SET Number03 = ISNULL(... | If you *really* want to use the SP to do the work you have to do it one at a time. Write a cursor to select all the rows with a NULL value and call the SP for each row passing Number01 and Number02.
I suspect your actual example is rather more complicated than the code you've shown. If you are able to go into more det... | Execute stored procedure SQL using value from table | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a query like this:
```
select
o.Name,
o.Family,
o.phone,
o.OBJECTID,
o.owner_id,
l.Licence_Contex,
l.Licence_title,
l.Id
from
[dbo].[owner_licence] as l,[dbo].[OWNER] as o
where o.[owner_id] =l.[Owner_ID]
And l.Id
NOT IN
(select l.id from [dbo].[owner_licence] as l,[dbo].[OWNER] as o
... | The subquery restricts the license to the one with the most maximum (qualified) id for each owner, so you should only get 1 license (and therefore 1 row) per owner.
```
select
o.Name,
o.Family,
o.phone,
o.OBJECTID,
o.owner_id,
l.Licence_Contex,
l.Licence_title,
l.Id
from
[dbo].[owner_licence] as l
join [dbo].[OWNER... | If you want this as one row then you will need to remove your last column from the the SElect clause.
Use Group by clause | Using group by in a sql query for remuving duplicates | [
"",
"sql",
"group-by",
""
] |
I have a table, which looks like the following:
Table `users`:
```
id points date
1 100 2014-07-01
2 500 2014-07-02
3 200 2014-07-01
4 100 2014-07-03
5 100 2014-07-01
6 400 2014-07-02
7 800 2014-07-02
8 200 2014-07-02
```
Now, how is it possible to ... | ```
SELECT SUM(`points`) AS points, `date`
FROM users
GROUP BY `date`
``` | This group-and-aggregate operation is a standard query pattern and can be solved following these steps1.
1. Use a [`GROUP BY date`](http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html) to aggregate the dates into groups, by date.
2. Select [`SUM(points)`](http://dev.mysql.com/doc/refman/5.0/en/group-by-func... | How to get a daily SUM of numbers with MySQL? | [
"",
"mysql",
"sql",
""
] |
I think I've seen answers for similar questions for MySQL, but I'm struggling to find an answer applicable to SQL Server 2005.
So I have a table like this:
```
| ID | RelationalID | Year
----------------------------
| 1 | A | 2014
| 2 | A | 2014
| 3 | B | 2014
| 4 | A |... | You can get the result based on ROW\_NUMBERs, but you need a rule how to assign them, I assumed it's based on the Id.
```
;WITH cte AS
(SELECT Id,
RelationalId,
year,
row_number()
over (partition by RelationalId, year
order by Id) as rn
FROM [YourTable]
)
select t1.id as... | Below Sql would give you the result you are looking for but as I said before complexity would depend on the original set of data you have in your table. Here is the SQL Fiddle - <http://sqlfiddle.com/#!3/d6300/24> - Good Luck!
```
;WITH CTE_Union AS
(SELECT
a.Id AS Id2014,
NULL AS Id2015,
a.RelationalId
... | SQL Server 2005: How to join table rows only once | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
My question is kind of easy but i'm still doubting after I created this transaction. If I execute the following code:
```
BEGIN TRANSACTION
DROP TABLE Table_Name
```
Can I perform a ROLLBACK TRANSACTION that recovers the dropped table? I'm asking because I don't know what happens in the 'Object Explorer' and I ... | `DROP TABLE` can be rolled back and it does not auto-commit. | This is incredibly easy to test.
```
create table TransactionTest
(
ID int identity primary key clustered,
SomeValue varchar(20)
)
insert TransactionTest
select 'Here is a row'
begin transaction
drop table TransactionTest
rollback transaction
select * from TransactionTest
``` | SQL Server: Does 'DROP TABLE' inside transaction causes an implicit commit? | [
"",
"sql",
"transactions",
"drop-table",
""
] |
I have three function calls in which I need all records in one column. I have been unable to achieve this and would appreciate a push in the right direction. I'm using a db2 database.
Function calls:
```
schema1.Usage ('element', 20140101, 20140714)
schema1.TOTAL_Usage ('element', 20140101, 20140714)
schema1.Usage ('... | If these are scalar functions, just put them in the `select`:
```
select schema1.Usage('element', 20140101, 20140714),
schema1.TOTAL_Usage('element', 20140101, 20140714)
schema1.CAPABILITY_Usage('element', 20140101, 20140714)/schema1.TOTAL_Usage('element', 20140101, 20140714) AS X(a)
from sysibm.sysdummy... | Your query should be fine with just a few small adjustments, I assume X is 1 row with 3 columns and not the other way around
```
select * from (
VALUES ( schema1.Usage ('element', 20140101, 20140714)
, schema1.TOTAL_Usage ('element', 20140101, 20140714)
, schema1.Usage ('element', 2014010... | Select from VALUES | [
"",
"sql",
"db2",
""
] |
I am working in SQL Server 2012 Management studio.
In a SQL query window, an insert into a `#table` is happening. It is expected to insert somewhere around 80 million rows with 3 `INT` columns each.
The query execution is going on.
Is there a way that I can track the no of rows in the `#table`? | Since you cannot run two queries in the same window simultaneously and temp tables are not accessible in other sessions if they are declared with a single #, you should try defining it with a double # in your insert query.
Then you could try querying it using WITH(NOLOCK).
Open a new query window on the same db and t... | One method is to query the DMVs using the temp table object id. You can get the local temp table object id from the session that created it using this query:
```
SELECT OBJECT_ID(N'tempdb..#table', 'U');
```
Then run the script below in another windows, supplying the object\_id value from the above query (-1180342868... | Track number of rows in a #table which the population is in progress | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I try to add the following code to a spring data jpa repository:
```
@Query("insert into commit_activity_link (commit_id, activity_id) VALUES (?1, ?2)")
void insertLinkToActivity(long commitId, long activityId);
```
But an app can't start with the exception:
> Caused by: org.hibernate.hql.internal.ast.QuerySynta... | I had to add `nativeQuery = true` to `@Query`
```
@Query(value = "insert into commit_activity_link (commit_id, activity_id) VALUES (?1, ?2)", nativeQuery = true)
``` | Use java object rather passing all parameters
```
@Modifying(clearAutomatically = true)
@Transactional
@Query(value = "insert into [xx_schema].[shipment_p] (gpn,qty,hscode,country_of_origin,created_date_time,shipment_id) "
+ "VALUES (:#{#sp.gpn},:#{#sp.qty}, :#{#sp.hscode} ,:#{#sp.countryOfOrigin}... | native insert query in hibernate + spring data | [
"",
"sql",
"hibernate",
"spring-data",
""
] |
since I am not as good with more complex SQL SELECT Statements I thought of just asking here, since it's hard to find something right on topic.
I got two tables who have exactly the same structure like
```
TABLE A (id (INT(11)), time (VARCHAR(10));)
TABLE B (id (INT(11)), time (VARCHAR(10));)
```
Now I want a single... | ```
SELECT COUNT(*) as count, 'tableA' as table_name FROM TABLEA WHERE id = '1'
union all
SELECT COUNT(*), 'tableB' FROM TABLEB WHERE id = '1'
``` | If you want the separate counts in a single row, you can use subqueries
```
SELECT
(SELECT COUNT(*) FROM TABLE A WHERE id = '1') a_count,
(SELECT COUNT(*) FROM TABLE B WHERE id = '1') b_count;
``` | Count uid from two tables who look the same sort by tablename | [
"",
"sql",
"select",
"count",
""
] |
My problem is, I want to store a person with multiple phone numbers in the database.
for a single variable for number will store only one number for each.
Now if I want to add another phone number it is creating another new record with the same details but the different number.
I want to display all these numbers tog... | You could use a second table to store the numbers, and link back with a Foreign Key:
```
PersonTable: PersonId, Name, etc..
```
The second table will hold the numbers...
```
NumbersTable: NumberId, PersonId(fk), Number
```
You could then get the numbers like this...
```
SELECT p.Name, n.Number from PersonTable p L... | You should create separate tables for Person and PhoneNumber.
```
CREATE TABLE Person(PersonId int IDENTITY(1,1) PRIMARY KEY)
CREATE TABLE Phone(
PersonId int,
PhoneNumber varchar(20),
CONSTRAINT PK_Phone PRIMARY KEY(PersonId,PhoneNumber),
CONSTRAINT FK_PersonId FOREIGN KEY(PersonId) REFERENCES Person... | How to store multiple values in single field in SQL database? | [
"",
"sql",
""
] |
In my SQL Server table, there is a column in which I have comma separated values.
For example: in column `AllSegmentsList` and the values in the column are like `'a, b, c,d, e'` .
Now, I my query I want to say
```
select *
from table
if one of the the entries out of all the comma separated values in that column... | It kind of depends on your data. If no value contains a space, following should work
```
select
*
from
table
where
replace(concat(',', slist, ','), ' ', '') like '%,b,%';
``` | this should work in all cases:
```
select * from tablename where replace(replace(','+allsegmentslist+',',', ',','),' ,',',') like '%,b,%'
``` | How to write a SQL query that selects one of the comma separated values in the column | [
"",
"sql",
"sql-server",
""
] |
I have records like this:
```
Column1 Column2
A Blue
A Blue
B Red
B Green
C Blue
C Red
```
Using `SELECT DISTINCT` I get this:
```
Column1 Column2
A Blue
B Red
B Green
C Blue
C Red
```
What I'd like to get:
```
Column1 Column2
B Red
B Gr... | Try this:
```
SELECT * FROM yourtable
WHERE Column1 IN
(SELECT Column1
FROM yourtable
GROUP BY Column1
HAVING COUNT(DISTINCT Column2) > 1
)
```
The `DISTINCT` in `COUNT` ensures that you only get those records where `Column2` has multiple distinct values. | I think this code will work in most systems:
```
SELECT Col1,Col2
FROM tbl
GROUP BY Col1,Col2
HAVING COUNT(*)<=1
```
See the results: <http://sqlfiddle.com/#!6/47285/8/0> | Get multiple records only using SELECT DISTINCT or similar | [
"",
"sql",
"select",
"distinct",
"multiple-records",
""
] |
I want to find a CONSTRAINT\_NAME in Oracle by SEARCH\_CONDITION.
```
SELECT * FROM ALL_CONSTRAINTS
WHERE TABLE_NAME = 'myTableName';
AND SEARCH_CONDITION = '"myColumn" IS NOT NULL';
```
ORA-00997: illegal use of LONG datatype.
How to query by SEARCH\_CONDITION? | SEARCH\_CONDITION is LONG so you can't use it for .... very much useful.
For this particular use, I suggest PLSQL routine to write the LONG col into a VARCHAR2(32767) and then apply the check on teh VARCHAR2 variable.
LONGs are an absolute pain.
Also, in your case you can restrict the dataset further by querying ALL... | You can write a simple stored procedure:
```
CREATE OR REPLACE FUNCTION get_search_condition(
p_owner ALL_CONSTRAINTS.OWNER%TYPE,
p_constraint_name ALL_CONSTRAINTS.CONSTRAINT_NAME%TYPE
) RETURN VARCHAR2
IS
v_long LONG;
BEGIN
SELECT SEARCH_CONDITION
INTO v_long
FROM ALL_CONSTRAINTS
WHERE CO... | Query to find Constraint by SEARCH_CONDITION | [
"",
"sql",
"oracle",
"constraints",
""
] |
I have these records below :
```
CustomerID | Name | Store | Quantity
1 | Elie | HO | 16
1 | Elie | S1 | 4
```
I would like to filter customers by taking only their max quantity?
I tried it with Max, but the problem I cannot render all the fields with it. If I add main.store in the... | Please try:
```
select * From tbl a
where a.Quantity=
(select MAX(b.Quantity) from tbl b where a.CustomerID=b.CustomerID)
``` | This is a good use of window functions:
```
with t as (
Select Name = cus.FIRST_NAME + ' ' + cus.LAST_NAME,
Store = cs.NAME,
Transaction_Number = count(ts.TRANSACTION_SUMMARY_ID) , cus.CUSTOMER_ID
from TRANSACTION_SUMMARY ts
inner join dbo.CUSTOMER cus on ts.CUSTOMER_ID =... | SQL query select record with Max | [
"",
"sql",
"sql-server",
""
] |
I have a table called `Platforms` with the following columns:
* id, name, img, template\_id
And another table called `Templates` with the following columns:
* id, tpl\_name, body
How can I select all platforms so all the rows have id, name, img, template\_id, tpl\_name.
`template_id` in `Platforms` = `id` in `Temp... | With a simple WHERE into a SELECT query :
```
SELECT p.id, p.name, p.img, p.template_id, t.tpl_name
FROM Platforms as p, Templates as t
WHERE p.template_id = t.id;
``` | Yes you can do it with one query and the method is called "a join between table Platforms and Templates":
```
SELECT * FROM Platforms
INNER JOIN Templates on Platforms.template_id = Templates.id
``` | Joining multiple sql queries together into one row | [
"",
"mysql",
"sql",
"select",
""
] |
I am working on an SQL Query which returns several rows of data from SQL tables on SQL Server using joins. But I just want the Query to return count of number of rows of data that is returned by following SQL Query
```
SELECT C.ContactID,
C.FirstName,
C.LastName,
SP.SalesPersonID,
SP.CommissionPct,
SP.SalesYTD,
... | I would just do this as two queries. One like you listed, and the other with a `COUNT(*)`:
```
SELECT COUNT(*)
FROM Person.Contact C
INNER JOIN Sales.SalesPerson SP
ON C.ContactID = SP.SalesPersonID
FULL OUTER JOIN Sales.SalesTerritory ST
ON ST.TerritoryID = SP.TerritoryID
ORDER BY ST.TerritoryID, C.LastName... | Use `@@ROWCOUNT` ([MSDN](http://msdn.microsoft.com/en-us/library/ms187316.aspx)). It returns the number of rows affected (selected, updated, deleted, etc) of the previous query.
```
SELECT C.ContactID,
C.FirstName,
C.LastName,
SP.SalesPersonID,
SP.CommissionPct,
SP.SalesYTD,
SP.SalesLastYear,
SP.Bonus,
ST.Ter... | Getting count of number of rows of data retrieved from several SQL Tables on an SQL Server | [
"",
"sql",
"sql-server-2012",
""
] |
I have a text input which upon keyup I want to update the options in an adjacent select field.
I have these 2 tables in my database:
**Models:**
```
ID modelName brandID
1 NA140 3
1 SRL 1
1 SRS 1
1 SRF 1
1 SMS 2
1 SMU 2
```
**Brands... | ```
SELECT DISTINCT b.brandName
FROM brands b
JOIN models m
ON m.brandID = b.id
WHERE m.modelName LIKE '%$variable%'
UNION
SELECT b.brandName
FROM brands b
JOIN models m
ON m.brandID = b.id
WHERE m.modelName NOT LIKE '%$variable%'
``` | I came up with a similar query (simplified):
```
select brandName from (
select b.brandName as brandName, m.modelName
from brands b join models m
on m.brandid = b.id
where m.modelName like '%sr%'
union
select b.brandName as brandName, m.modelName
from brands b join models m
on m.brandid = b.id
where m.modelName ... | Tricky MySQL JOIN query | [
"",
"mysql",
"sql",
"join",
""
] |
We've got 7 guys travelling in Poland ( ;) ). The problem is to find up to three next cities they visited from the time they visited Warsaw. If one guy visits Warsaw twice, it is also counted as a starting point for the next journey.
For example guy 1 have had not only a journey - Warsaw, Cracow, Warsaw, Gdansk, but al... | If you are using SQL Server 2012 or later version, you can fairly easily [solve the problem](http://sqlfiddle.com/#!6/1e595/1 "Demo at SQL Fiddle") with the help of the [LEAD() analytic function](http://technet.microsoft.com/en-us/library/hh213125.aspx "LEAD (Transact-SQL)"):
```
WITH ThreeDestinations AS (
SELECT
... | Solution using `Row_Number()` and `Pivot`:
```
select guy,[1] as First, IsNULL([2], '') as Second, IsNUll([3], '') as Third, IsNull([4], '') as Forth
from (
select row_number() over (partition by guy order by guy, date) as number, city, guy
from voyage
) x
pivot
(
max(city)
for number in ([1], [2],... | Selecting three rows after the one that meets the condition | [
"",
"sql",
"sql-server",
"database",
""
] |
I need to create a copy of a database table.
I require to set the TEXTIMAGE\_ON value which can only be created at Creation time and not with ALTER TABLE afterwards.
I am also not allowed to alter any database properties beforehand. So basically NOT:
```
ALTER DATABASE backoffice MODIFY FILEGROUP filegroup DEFAULT
``... | This should get you there mostly. You may still have to refine it per requirement. Hope this helps
```
DECLARE @TableName SYSNAME = 'TableName';
DECLARE @SQL VARCHAR(MAX),
@ColumnList VARCHAR(MAX),
@Schema VARCHAR(250);
SELECT @Schema = QUOTENAME(TABLE_SCHEMA)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @Table... | This will at least get you started. You have some work still to do here but this should give you the information you need to build some dynamic sql for this.
```
declare @TableName sysname = 'YourTable'
select *
from sys.columns c
join sys.types t on c.user_type_id = t.user_type_id
where c.object_id = object_id(@Tabl... | Cloning a Table without using SELECT TOP (0) * INTO | [
"",
"sql",
"sql-server",
"sql-scripts",
""
] |
I have a query on a 500 000 row table.
Basically
```
WHERE s3_.id = 287
ORDER BY m0_.id DESC
LIMIT 25
```
=> Query runtime = 20ms
```
WHERE s3_.id = 287
ORDER BY m0_.created_at DESC
LIMIT 25
```
=> Query runtime = 15000ms or more
There is an index on created\_at.
The Query plans are completely different.
Unfort... | It turned out to be an index issue. The NULLS behaviour of the query was not coherent with the index.
```
CREATE INDEX message_created_at_idx on message (created_at DESC NULLS LAST);
... ORDER BY message.created_at DESC; -- defaults to NULLS FIRST when DESC
```
## solutions
If you specify NULLS in your index or que... | ### Fix your query
Your `WHERE` condition is on a table that's joined via `LEFT JOIN` nodes. The `WHERE` condition forces the joins to behave like `[INNER] JOIN`. That's pointless and may confuse the query planner, especially with a query that has a lot of tables and therefore *many* possible query plans. By setting t... | Changing ORDER BY from id to another indexed column (with low LIMIT) has a huge cost | [
"",
"sql",
"postgresql",
"postgresql-9.1",
""
] |
I have a table which includes customer transactions. These transactions could have `StartDate` and `EndDate`. If the `EndDate` hasn't come, then the field is NULL. In my query, if I select for example the transactions that started today and don't have enddate (which is `NULL`) I don't get the right results. However, if... | ```
AND (t.EndTime <= @EndDate OR t.EndTime IS NULL)
```
or:
```
AND COALESCE(t.EndTime, @EndDate) <= @EndDate
``` | Change the last part of the WHERE clause like so
```
AND t.EndTime IS NULL
``` | SQL Query - Range two dates - including nulls | [
"",
"sql",
"sql-server",
""
] |
This is admittedly a "Friday" question..
When I look up [the definition of](https://www.google.com/search?q=define%20primary%20key&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a#q=define%20primary%20key&rls=org.mozilla:en-US:official&safe=off) "primary key" it says :
> In Oracle, a primary key ... | A primary key is backed by an index, and [an index key can only have 32 columns](http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_5012.htm#SQLRF53989). So it's an inherited restriction from the index. There probably wasn't much point adding additional restrictions on the primary key itself, as the index... | It can be the case having a fact table in the star Schema with as much dimensions. The fact record would be identified by Dimension keys. Having said that, I don't really think this would make sense to physically create such a constraint. You usually can control uniqueness in your ETL-Processes and this fact table woul... | Is there ever a situation where you ever need a primary key with 32 fields? | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.