Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
This should (hopefully) be a fast one, unfortunately I am a little bit slow today and need your help.
I've basically wrote an INSERT statement with the following structure in order to insert multiple rows with a single statement:
```
INSERT INTO TABLE_TO_INSERT_INTO
SELECT
-- ...,
-- ...,
-- ...,
(S... | As you are using Oracle, then I would suggest you to use [SEQUENCE](http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_6015.htm)
```
CREATE SEQUENCE customers_seq
START WITH 1000
INCREMENT BY 1
NOCACHE
NOCYCLE;
```
In your query
```
SELECT customers_seq.nextval from yourTable;
```
The above ... | Unless you are inserting into SOME\_TABLE (which you aren't), (SELECT MAX(ID)+1 FROM SOME\_TABLE) As ID will always return the same value because the MAX(ID) is not affected by additional rows in TABLE\_TO\_INSERT\_INTO.
You could in theory use some kind of row number offset plus your MAX(ID) value BUT I would strongl... | Incrementing a value in a mutliple row INSERT statement | [
"",
"sql",
"database",
"oracle",
""
] |
I have a decently large table (~20 million) with a primary key column and another column with large text strings (~ 250 char). The primary key column is all unique but the text strings have repeats. I want to remove all redundant text strings and “distinctify” the table or create a new table to the same affect.
I want ... | Your memory overflow is likely due to returning such a large resulset back to SSMS. If you `Select min(ID), TextColumn Into TableXYZ Group By TextColumn`, you should get around this issue. Once the 'Distinctified' results are in a separate table, you can then go about deleting/archiving the records in the original tabl... | At one level this is the same question as that asked in [How can I remove duplicate rows?](https://stackoverflow.com/q/18932/73226).
You could use [the `ROW_NUMBER` approach](https://stackoverflow.com/a/3822833/73226) but this will require sorting the 20 million rows. Or [the `GROUP BY` approach](https://stackoverflow... | Distinct Grouping on Large table | [
"",
"sql",
"sql-server",
""
] |
I could use some advice in how to create my select statement, so it will work with the check-in and check-out dates. I have 2 tables: Rooms and Booking. To help you understand, they look like this:
```
Rooms table:
Room number (prim-key)
Type
Price
Booking table:
BookingId (prim-key)
Check-In date:
Check-Out date:
Ro... | I think Tim misses one case -- using Between make the logic clearer maybe?
*EDIT: Nevermind, Tim's is correct -- here is another way to do it.*
the cases -- our checkin or checkout is sometime between when the room is used or our checkin and checkout "surround" when the room is used.
```
SELECT r.*
FROM Room r
WHERE... | ```
SELECT r.*
FROM Room r
WHERE NOT EXISTS
(
SELECT 1 FROM Booking b
WHERE b.RoomNumber = r.RoomNumber
AND
(
(@CheckIn >= b.CheckIn AND @CheckIn <= b.CheckOut)
OR (@CheckIn <= b.CheckIn AND @Checkout >= b.CheckIn)
)
)
``` | Checking available room resevation between check-in and check-out date with SQL in ASP.net | [
"",
"sql",
"asp.net",
""
] |
I am trying to 'obfuscate' data in a SQL database for the purposes of testing. I have a single field in a single table where I want the values to be replaced with a random string - however the same string has to have the same value. So for example:
```
Cat
Dog
Cat
Fish
Monkey
```
Would have to replaced with
```
YuW ... | You should use [hashing](https://msdn.microsoft.com/en-us/library/ms174415.aspx):
```
SELECT HashBytes('MD5', yourcolumnname)
```
This will give you a non-reversible 'obfuscation' for which the same input value will return the same value.
Edit: if you don't want MD5 HashBytes can handle MD2, MD4, MD5, SHA, SHA1, or ... | If it's just for testing purpose and a matter of interest, I'd do it like that:
1. Put distinct records into temporary table and add a new column, let's name it `[Randomized]`
2. Generate desired random text and make sure it has same `LEN()` as actual text (Use `LEFT()`, `RIGHT()`, `SUBSTRING()` or any other function ... | Generating the same random string in SQL for a set of rows | [
"",
"sql",
"sql-server",
"random",
""
] |
I gotta problem. When I run the below code I get an error saying:
invalid length parameter passed to the right function. What does that mean and how can it go away? Its to parse a name like smith, steve s to steve r smith in columns firstname, middlename and lastname
```
UPDATE table5
SET lastName = LEFT(Name, CHARIN... | The error is because `CHARINDEX()` is returning 0 and `SUBSTRING()` require at number bigger than 0. Your assumption is correct string without middle name will give you error.
Can you check this fiddle and let me know if that is the format you are using for name. Because the Gordon Linoff query seem to be working for ... | I would prefer to write a function, Here is the code.
```
IF object_id(N'udf_NameSplitter', N'FN') IS NOT NULL
DROP FUNCTION udf_NameSplitter
GO
CREATE FUNCTION udf_NameSplitter
(
@FullName VARCHAR(50),
@NameSplitCharacter CHAR(1),
@NamePart CHAR(50) /*FN-firstname,MN-middlName,LN-lastName*/... | Error: invalid length parameter passed to the right function in name parsing script | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Suppose I have the following SQL (which can be [run against the Data Explorer](https://data.stackexchange.com/meta.stackexchange/query/336425/fiddle-for-so-question-31417041), if you'd like):
```
SELECT COUNT(Id) AS "Count"
INTO #temp
FROM Posts
PRINT (SELECT * FROM #temp)
```
This produces an error:
> "Sub... | No this isn't possible according to the grammar.
The only way of doing it other than assigning to a variable at the same scope would be to wrap the `select` in a UDF as far
as I can see.
The [documentation](https://msdn.microsoft.com/en-gb/library/ms176047.aspx) States
> PRINT msg\_str | @local\_variable | string\_e... | As far as I can tell, nope. Even a statement as simple as `PRINT (SELECT 1)` or `PRINT (SELECT TOP (1) 1)` fails.
My guess is that PRINT simply won't execute SQL of any kind to prevent possible injections. It's PRINT, after all, not EXEC. It's meant to return a string message to the client. | Can I treat a subquery with one row and one column as a scalar? | [
"",
"sql",
"sql-server",
""
] |
I want to add a new column to a table to record the number of attributes whose value are null for each tuple (row). How can I use SQL to get the number?
for example, if a tuple is like this:
```
Name | Age | Sex
-----+-----+-----
Blice| 100 | null
```
I want to update the tuple as this:
```
Name | Age | Sex | nNULL... | Possible **without spelling out columns**. Unpivot columns to rows and count.
The aggregate function [`count(<expression>)`](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) only counts non-null values, while [`count(*)`](https://www.postgresql.org/docs/current/functions-aggr... | In Postgres, you can express this as:
```
select t.*,
((name is null)::int +
(age is null)::int +
(sex is null)::int
) as numnulls
from table t;
```
In order to implement this on an unknown table, you will need to use dynamic SQL and obtaining a list of columns (say from `information_sch... | Count the number of attributes that are NULL for a row | [
"",
"sql",
"postgresql",
"count",
"null",
"plpgsql",
""
] |
This almost works. I get an error at the last line that looks like it's complaining about the C1 reference. Is there a simple way around this? There is nothing wrong with the query or connection.
```
Dim CmdString As String
Dim con As New SqlConnection
Try
con.ConnectionString = PubConn
CmdSt... | The alias C1 is used by SQL Server and is not persisted to the result set. Have you taken this query into SQL Management Studio to see the results?
Since you requested all columns (\*) and joined to the Contacts table twice, you'll end up with duplicate column names in the result. For example, if the Contacts table ha... | You would not include the "C1" table alias as part of your column name. It will be returned from your query as Contact\_Business\_Phone.
For accessing multiple rows you could use the indexer as you are in the example above "Rows(0)" by placing your With block into a For loop and accessing the "Rows(i)" with your loop ... | How do I access multiple records from the same table using SQLDataAdapter? | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
Suppose, `order_id` `4646`, `4647` and `4648` are from same customer.
```
SELECT customer_id FROM orders WHERE order_id IN (4646, 4647, 4648)
```
Result:
```
customer_id
2589
2589
2589
```
Every customer has a `gcm_registration_token`.
```
SELECT gcm_registration_token FROM customer_details WHERE customer_id IN (2... | You can use [**INNER JOIN**](http://www.w3schools.com/sql/sql_join_inner.asp) in following:
```
SELECT gcm_registration_token
FROM orders o
INNER JOIN customer_details d ON o.customer_id = d.customer_id
WHERE order_id IN (4646, 4647, 4648)
``` | Use `JOIN` like this:
```
SELECT c.gcm_registration_token
FROM orders o
JOIN customer_details c ON c.customer_id = o.customer_id
WHERE o.order_id IN (4646, 4647, 4648)
``` | Need multiple rows with same value IN OPERATOR | [
"",
"sql",
""
] |
**Background:**
Table A has columns `userid`, `friend_id`. It stores all `friend_id`s of user having `userid`.
e.g. Table A
```
-----------------------
| userid | friend_id |
|---------------------|
| 3 | 5 |
| 3 | 6 |
| 3 | 7 |
| 3 | 8 |
| 3 | 9 ... | Using `NOT EXISTS`:
```
SELECT a.*
FROM TableA a
WHERE
a.userid = @userid
AND NOT EXISTS(
SELECT 1
FROM TableB b
WHERE
b.blocked_userid = a.userid
AND b.blocker_userid = a.friend_id
)
```
[**SQL Fiddle**](http://sqlfiddle.com/#!6/4669d/1/0)
---
Using `LEF... | ```
select friend_id,friend_name from tableA a
Left Join tableB b on a.friend_id=b.blocker_userid and b.blocked_userid = @userid
where a.userid = @userid and b.blocker_userid is null
``` | SELECT query with exclusions specified in other table - 1 | [
"",
"mysql",
"sql",
"database",
""
] |
I have a table which has the below schema definition :
```
CREATE TABLE `currency` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` char(3) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (... | The error
> Error on rename of ... errno: 150 - Foreign key constraint is incorrectly formed)
happens because you are trying to drop a referenced primary key, even though you are disabling foreign key constraint checking with `SET FOREIGN_KEY_CHECKS=0;`
Disabling foreign key checks would allow you to temporarily del... | Running
```
ALTER TABLE myTable DROP PRIMARY KEY;
```
caused an error like
```
`Error Code: 1025. Error on rename of 'some_name' to 'another_name' (errno: 150 - Foreign key constraint is incorrectly formed)`
```
> Dropping, creating new column and adding it as a primary key **all
> as a single command** works like ... | Cannot change primary key because of "incorrectly formed foreign key constraint" error | [
"",
"mysql",
"sql",
""
] |
I have a table like this:
```
+-------+--------------+--------------+-------------+-------------+-------------+-------------+
| Study | Point_number | Date_created | condition_A | condition_B | condition_C | condition D |
+-------+--------------+--------------+-------------+-------------+-------------+-------------+
|... | This should help you work out what you need to do:
```
with sample_data as (select 1 id, 1 ca, 0 cb from dual union all
select 2 id, 1 ca, 1 cb from dual union all
select 3 id, 1 ca, 1 cb from dual union all
select 4 id, 0 ca, 0 cb from dual union all
... | Your original query:
```
select *
from my_table
where point_number <= 200;
```
Should do what you want -- retrieve values of `point_number` less than 200. It should do this for each group.
If you want *200* values in each group, then something like this might be what you really want:
```
select t.*
from (select t.*... | Any way to avoid a union in this Oracle query? | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
have something kinda weird here. I have a database that's called FLDOC. In it has a column called SENTENCE that contains 7 numbers that represent a length of time.
```
example:
0050000
0750000
0000600
0040615
0000110
```
In those 7 digits is a length of type since the digits represent YYYMMDD
So what I'd like is a s... | `CONCAT` is new to SQL Server 2012. If you have previous version of SQL Server, you could do something like this instead to achieve your desired output:
```
SELECT sentence
,(
CASE
WHEN cast(left(sentence, 3) AS INT) > 0
THEN cast(cast(left(sentence, 3) AS INT) AS VARCHAR(3)) +... | You can do this with `Concat` as well:
```
Select Concat
(
Left(SENTENCE, 3), 'Y ',
SubString(SENTENCE, 4, 2), 'M ',
Right(SENTENCE, 2), 'D'
)
From Table
```
To condense the expression as in your example, this can be used as well:
```
Select Concat
(... | Reformatting data in column | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a column called "**SYS\_CREAT\_TS**". I want the query to fetch the REV data where Status code is 2 and from the latest timestamp where status code is 2.
```
SELECT RVSN FROM DATA_STUS WHERE DATA_STUS_CD = 2 AND SYS_CREAT_TS IN MAX(SYS_CREAT_TS);
```
**Some more detail**
Without the latest timestamp comparis... | This will work:
```
select rvsn
from (
select rvsn, row_number() over (order by sys_creat_ts desc) as rn
from data_stus
where data_stus_cd = 2
) where rn = 1;
``` | ```
SELECT RVSN
FROM DATA_STUS
WHERE DATA_STUS_CD = 2
AND SYS_CREAT_TS = (SELECT MAX(SYS_CREAT_TS)
FROM RVSN
WHERE DATA_STUS_CD = 2)
```
Would something like this work for your issue? | How to get the latest timestamp (Max) in a column | [
"",
"sql",
"oracle",
""
] |
I am working on an sql query where i have to find last 10 years. Suppose this is 2015 then then the query should return 2015,2014,2013... and so on. For this i have used the following query-
```
select top 10 DATEPART(Year,getdate()) order by DATEPART(Year,getdate()) desc
```
But the above query is returning only sin... | Try this:
```
with yearlist as
(
select (DATEPART(Year,getdate())-10) as year
union all
select yl.year + 1 as year
from yearlist yl
where yl.year + 1 <= YEAR(GetDate())
)
select year from yearlist order by year desc;
``` | You can do It in following:
```
DECLARE @YearsToPass INT
SET @YearsToPass = 10
;WITH cte AS
(
SELECT DATEPART(YY, GETDATE())- @YearsToPass + 1 as Years
UNION ALL
SELECT Years + 1 as Years
FROM cte
WHERE Years + 1 <= YEAR(GETDATE())
)
SELECT Years
FROM cte
ORDER BY Years DESC
```
Simple set... | How to find last 10 years using sql query | [
"",
"sql",
"sql-server",
""
] |
Suppose I have 2 tables `T1` and `T2` as follows
`T1`:
```
bag_id bag_type capacity
------|--------|--------
1 A 500
2 A 300
3 A 100
4 B 200
5 B 100
```
`T2`:
```
item_type item_amount
---------|-----------
A 850
B 300
```
... | You are looking for a cumulative sum. Something like this:
```
select t1.*,
(case when cumecap <= t2.item_amount
then t1.capacity
when cumecap - t1.capacity <= t2.item_amount
then t2.item_amount - (cumecap - t1.capacity)
else 0
end) as allocated_capac... | This should do the trick:
```
select t1.bag_id
, t1.bag_type
, t1.capacity
, least( t1.capacity -- don't over fill the bag
, greatest( 0 -- don't under fill the bag
, t2.item_amount -- to be allocated
- nvl(sum(t1.capacity) -- less previous alloca... | Oracle aggregation function to allocate amount | [
"",
"sql",
"oracle",
"oracle11g",
"aggregate-functions",
"data-warehouse",
""
] |
I have table name `tblAttend` in which one column named `WorkHrs` is of datatype `varchar`.
The result of simple select query is

I sum this column's value and get result in seconds my query is
```
select sum(DATEDIFF(SECOND, '0:00:00', WorkHrs )) ... | Try splitting each time into its component parts by converting the time to a string and then multiplying by the number of seconds relevant to each part.
Data conversion to integer is implicit
```
select Sum(Left(WorkHrs,2) * 3600 + substring(WorkHrs, 4,2) * 60 + substring(WorkHrs, 7,2))
from tblAttend
``` | Try:
```
DECLARE @DURATION TIME = '01:43:24'
SELECT DATEDIFF(SECOND, '1/1/1900', CONVERT(DATETIME, @DURATION))
``` | How to convert hh:mm:ss to seconds in SQL Server with more than 24 hours | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I can do something like this:
```
select
case a.x > 1 then a.bananas else a.pajamas end
from my_table a;
```
But when I try to tweak it like this:
```
select
case a.x > 1 then a.bananas, a.pajamas else a.strawberries, a.peaches end
from my_table;
```
it says I have an error in my syntax. How can I select arbitr... | You need a separate `CASE` for each column:
```
SELECT
case a.x > 1 then a.bananas else a.pajamas end as bananas_or_pajamas,
case a.x > 1 then a.strawberries else a.peaches end as strawberries_or_peaches,
....
``` | CASE is a function, and can only return a single value. You can only use it to switch the value of one field in a query. Another option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.
Using c... | SQL multiple-select case statement | [
"",
"mysql",
"sql",
""
] |
I use this method to encrypt my string:
```
RETURN RAWTOHEX(DBMS_CRYPTO.HASH(SRC=>to_hash, TYP=>dbms_crypto.HASH_MD5));
```
Now I have the encrypted MD5 string like:
> F267E16E70C2528280A487D5D13617A6
Is there a way to decrypt this code to get the start-string again? | MD5 is a hashing algorithm, not really intended for encryption or decryption.
So, no, there is no way to get the start-string again. Actually, given a hash, there would be many potential start-strings it could come from. | The hash function is not [isomorphic](https://en.wikipedia.org/wiki/Isomorphism), i.e. it is not possible in general case to invert the function and get the unique original value.
This is is something very different to beeing "safely decoded". If there is additional knowledge e.g. about the lenght of the string, it is ... | Oracle Hash MD5 decryption | [
"",
"sql",
"oracle",
"plsql",
"md5",
""
] |
I have a query in which the user can choose which columns they wish to search on (each column has a corresponding filter on the web). I've used the NULL method to try and ignore the parameter if it is passed into the DB as NULL. Having all fields NULL works as expected and returns all records, but when attempting to fi... | As I told above, I perhaps would go for dynamic code here, since your query contains a lot of `OR` statements. I've rewritten your procedure like that. Please leave a comment or ideas.
What I can think of all records not comming back - you hardcoded `@starttime` and `@finishtime`, just deal with them. I tried to do it... | You need parentheses:
```
WHERE UserChats.SiteKey = @SiteKey AND
(UserChats.Invited = @invited OR @invited is NULL) AND
(UserChats.StartTime = @starttime OR @starttime = '1900-01-01') AND
(UserChats.FinishTime = @finishtime OR @finishtime = '1900-01-01') AND
. . .
``` | Stored Procedure not returning filtered results when using NULL to ignore parameter if empty | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
In a table, I have a column that contains a few records with accented characters. I want a query to find the records with accented characters.
If we have records like as below:
```
2ème édition
Natália
sravanth
```
query should pick these records:
```
2ème édition
Natália
``` | You can use the REGEXP\_LIKE function along with a list of all the accented characters you're interested in:
```
with t1(data) as (
select '2ème édition' from dual union all
select 'Natália' from dual union all
select 'sravanth' from dual
)
select * from t1 where regexp_like(data,'[àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎ... | The [ASCIISTR function](https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/ASCIISTR.html) would be another way to find accented characters
> ASCIISTR takes as its argument a string, or an expression that
> resolves to a string, in any character set and returns an ASCII
> version of the string in the... | Find the accent data in table records | [
"",
"sql",
"oracle",
""
] |
I'm looking to find the average number of employees for the first half of 2015. Thats the head count of each month, Jan-Jun / 6 (months). This number is the desired result.
For example, lets just do 3 months for simplicity's sake. Jan had 100, Feb had 105, and Mar had 103. 308/3 = 102.7 average employees.
Unfortunate... | Here is [SQL Fiddle](http://sqlfiddle.com/#!6/0796f/3/0) with your updated sample data. There are two queries there: first returns just one average number, second returns daily numbers to help understand how it works. Follow the dates and you can see how the number changes as people come and go.
---
For each person y... | Go with @VladimirBaranov's answer for a generic solution.
But in your special case you might not need to calculate the employees per month and then average it. Simply summing the number of months employed within the requested range and then dividing it by 6 returns the same result.
```
SELECT
-- approximate month... | Find a YTD Employee Average | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a table `Contacts`, parent to table `Activity`. I would like to select the latest activity for each contact, but getting more than one row.
This is my query:
```
select top 30
*
from
Contacts o, Activity d
where
o.ID = d.contact
and d.ID > 401061
and Last_Action is null
order ... | You can use `row_number()` to number each contact's activities. In an outer query, you can filter down to only the latest activity per contact:
```
select top 30 *
from (
select row_number() over (
partition by o.ID
order by d.activity_date desc) as rn
, ... | Here's a way using `not exists` that will work on most dbs. You're basically selecting each activity per contact where a newer activity does not exist (therefore it's the latest activity).
```
select top 30 * from activity a
join contact c on c.id = a.contact
where not exists (
select 1 from activity b
where b... | Using Top in SQL Server 2012 | [
"",
"sql",
"sql-server",
""
] |
I am trying to create an app where users can create and take part in challenges. The idea is that one user can create many challenges but each challenge can only be created by one user. Many users can enter one challenge and each entry can only be part of one challenge. Users can enter a challenge more than once
My co... | I would see the schema looking something like this:
```
User
----
userId PK
Challenge
----
ChallengeId PK
creatingUserId FK to user.UserId
Entry
----
EntryId PK
ChallengeId FK to challenge.challengeId
UserId FK to user.UserId
```
this would allow only a single author of a challenge, but multiple participants (`Entr... | I agree to @Kritner answer and mine is an addition. To track which entry belongs to which user, you can write something like:
```
select u.userName, e.EntryId from T_Users u
inner join T_Entries e on e.userId = u.userId
``` | How to create join where a table is associated with more than one other table | [
"",
"sql",
"database-design",
""
] |
I have a query that groups easily. I need to get the groups that have exactly the same records to another table (relationship).
I'm using ANSI-SQL under SQL Server, but I accept an answer of any implementation.
For example:
Table1:
```
Id | Value
---+------
1 | 1
1 | 2
1 | 3
2 | 4
3 | 2
4 | 3
```
Table... | You can try the following:
```
select t1.Id
from Table2 t2
join Table1 t1 on t1.value = t2.value
group by t1.Id
having count(distinct t1.value) = (select count(*) from Table2)
```
[**SQLFiddle**](http://sqlfiddle.com/#!9/03045/5) | To get the same sets use an inner join:
```
SELECT Table1.Id
FROM Table1
INNER JOIN table2 ON table1.id=table2.id
GROUP BY Table1.Id
HAVING ...? --
``` | Get groups that are exactly equal to a table | [
"",
"sql",
"sql-server",
"ansi-sql",
""
] |
While practicing in SQL here <http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_join> i made up a task for myself - need to compose a table using INNER JOIN that will contain CustomerID, EmployeeID, ContactName of a customer, and employee's last and first names WHERE Employee's first name is contained in C... | This works
```
SELECT DISTINCT Customers.CustomerID, Customers.ContactName AS CustomerContactName, Employees.EmployeeID, Employees.FirstName AS EmployeeFirstName, Employees.LastName AS EmployeeLastName
FROM Customers
INNER JOIN Employees
ON Customers.ContactName LIKE "%"+Employees.FirstName+"%"
```
Results in:
```
... | The first thing to note is that the two queries are not comparable, If first name was `Janette`, and contact name was `Janet Jackson`, then the both values statisfy `LIKE '%Janet%'`, but `Janet Jackson` does not contain `Janette`, so the join condition is not met.
Secondly, I think you should be using single quotes fo... | LIKE in INNER JOIN doesn't work | [
"",
"sql",
""
] |
I want to write a TSQL query that independently checks a set of columns in a table to see which ones contain at least one non-null value. Each column's check should return T/F (1/0) accordingly.
The first thing that came to mind was to use the `COUNT` aggregate function. Since `COUNT(expression)` excludes nulls from t... | You could try something like this:
```
;WITH cte AS (
SELECT * FROM dbo.Table WHERE TimeStamp BETWEEN @StartTimeStamp AND @EndTimeStamp
)
SELECT COUNT(s1.Col1) as Col1, COUNT(s2.Col2) as Col2,
COUNT(s3.Col3) as Col3, COUNT(s4.Col4) as Col4
FROM
(SELECT TOP 1 Col1
FROM cte
WHERE Col1 IS NOT NULL) s1 CROSS J... | If you have indexes on the columns, the following may be faster:
```
select (case when exists (select 1
from table t
where t.TimeStamp BETWEEN @StartTimeStamp and @EndTimeStamp and
column1 is not null
)
... | TSQL: Check columns for at least one non-null value | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have following code -
```
SELECT
BR_CSNO AS [PARTY_KEY],
'W' AS [PHONE_TYPE_CD],
ISNULL( LTRIM( RTRIM( FAC_TELNO ) ), '0' ) AS [PHONE_NUM],
NULL AS [UPDATE_DT],
GETDATE() [BATCH_DT]
FROM
BASE B
```
I get following result -
 ), '0' ) AS [PHONE_NUM],
NULL AS [UPDATE_DT],
GETDATE() [BATCH_DT]
FROM
BASE B
``` | SQL has two functions related to nulls.
1. IsNull, which takes two parameters, a potentially null value and, and a replacement value if the original value is null. IsNull(null, 0) = 0
2. NullIf, which takes two parameters and COMPARES THEM. If the comparison returns true, then null is returned, if the comparision is f... | ISNULL not replacing with NULL | [
"",
"sql",
"sql-server",
"sql-server-2008",
"isnull",
""
] |
I am working on queries on a large table in Postgres 9.3.9. It is a spatial dataset and it is spatially indexed. Say, I have need to find 3 types of objects: A, B and C. The criteria is that B and C are both within certain distance of A, say 500 meters.
My query is like this:
```
select
school.osm_id as school_osm... | This query should go a long way (be *much* faster):
```
WITH school AS (
SELECT s.osm_id AS school_id, text 'school' AS type, s.osm_id, s.name, s.way_geo
FROM planet_osm_point s
, LATERAL (
SELECT 1 FROM planet_osm_point
WHERE ST_DWithin(way_geo, s.way_geo, 500, false)
AND amen... | The 3 sub-selects that you use are very inefficient. Write them as `LEFT JOIN` clauses and the query should be much more efficient:
```
SELECT
school.osm_id AS school_osm_id,
school.name AS school_name,
school.way AS school_way,
restaurant.osm_id AS restaurant_osm_id,
restaurant.name AS restaurant_name, ... | Spatial query on large table with multiple self joins performing slow | [
"",
"sql",
"postgresql",
"postgis",
"spatial",
"postgresql-performance",
""
] |
I'm writing a procedure and I need to compare dates against a specific date in the future. I want to default to the last day of February. So if I'm running the report in January or February, the date will be Feb 28 (or 29 if a leap year) of the same year. If I'm running the report in March or later, the date will be Fe... | You're essentially using March 1st as the start of the year, so you could use the `add_months()` function to adjust the date forward 10 months, find the start of that (actual calendar) year, and then find the first day of March in that adjusted year, and find the day before that:
```
add_months(trunc(add_months(sysdat... | You can use `last_day` to get the last day of the month and `add_months` to add a number of months to a date. There is probably a cute mathemetical way to avoid the `case` statement as well that I'm not thinking of
```
-- Showing the results that you would get if you ran on various dates.
-- In reality, you'd get rid ... | In Oracle, find the next specific date | [
"",
"sql",
"oracle",
"date",
"oracle11g",
""
] |
As I add a View to SQL Server I get this error:
```
Incorrect syntax near the keyword 'DECLARE'
```
because I have to Declare first a tempTable `Currency` then insert some values in it from `Currecy` then retrieved it and `Join` it to `Items` table where the `Select` Statement start
My Question is, does Creating a v... | SQL Server defines CREATE VIEW as following:
```
CREATE VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ]
[ WITH <view_attribute> [ ,...n ] ]
AS select_statement
...
```
That means after AS you have to use a single select statement.
If you like, you can use various techniques to avoid filling your temporary... | Views do not allow creation of temporary tables. You need to use a Stored procedure | Adding a SQL View Error | [
"",
"sql",
"sql-server",
"view",
""
] |
Is there a way I can view the progress of a query? For example, SELECT queries that have to fetch large amount of data. If a table contains 100 rows, can SQL report which row is processing at the moment? That would be 1 to 100 progress.
I'm not wanting to view the progress in time left or something related with time b... | It is possible!
By the way, note, that e.g. mytop - monitoring tool from CLI for MySQL and MariaDB has already implemented that function.
**(1) In MariaDB**
```
SHOW FULL PROCESSLIST;
+-----+------+-----------+------+---------+------+-------+-----------------------+----------+
| Id | User | Host | db | Comma... | You can try `show processlist;` in mysql, it will give you the time query has taken as well as the current step query is in like fetching,sending etc. | SQL view progress of query | [
"",
"mysql",
"sql",
"progress",
""
] |
I use a table in PostGres for providing authorization in a SpringBoot web app that connects to a PostGres database. I want to initialize this table with a default admin entry if the table is empty. I am doing this from within schema.sql file Here is the code I have attempted so far:
```
CREATE TABLE IF NOT EXISTS publ... | This is how I finally managed to do what I want:
```
CREATE TABLE IF NOT EXISTS public.jdbcauth
(
username VARCHAR(32),
password VARCHAR(32) default NULL,
role VARCHAR(32) default NULL,
enabled INT default 0,
PRIMARY KEY(username)
);
INSERT INTO public.jdbcauth (username, password, role, enabled)
... | Don't you need a "THEN"?
```
IF EXISTS (SELECT 1 FROM public.jdbcauth) THEN
INSERT public.jdbcauth (username, password, role, enabled) VALUES ('admin', 'admin', 'ADMIN', '1');
``` | Initializing an Empty Table using schema.sql in Spring Boot | [
"",
"sql",
"postgresql",
"spring-boot",
""
] |
I have a few tables
1. clubs -> contains information on different clubs
2. clubs-leagues -> contains information about different leagues hosted by the clubs
3. codes -> contains description of short hand codes ive used to make data entry a little easier
clubs-leagues has a field that contains the id of the clubs to f... | As indicated in comments, you need to use `LEFT JOIN` from clubs to leagues to get all clubs regardless of league membership. Your SQL could look like this:
```
SELECT club.*, sport.name AS sport, code.description AS statusText,
code1.description AS ageGroup, code2.description AS gender,
leagues.name AS league... | Use `LEFT JOIN` or `RIGHT JOIN` instead of `JOIN` for including all values from left|right tables, even if right|left tables have not matching rows. | Join table if table has results | [
"",
"mysql",
"sql",
"join",
""
] |
I found SQL function which get second as input parameter and return seconds in dd:hh:mm:ss format e-g for `93600` seconds it returns `1:02:00:00`
it means 1 day 2 hours 0 minutes and 0 seconds.
Function that i used is :
```
FUNCTION [dbo].[udfTimeSpanFromSeconds]
(
@Seconds int
)
RETURNS varchar(15)
AS
BEGIN
DEC... | You can do this with math
```
DECLARE @sec INT = 93600
SELECT
CONVERT(VARCHAR(10), (@sec / 3600)) + ':' +
RIGHT('0' + CONVERT(VARCHAR(2), ((@sec % 3600) / 60)), 2) + ':' +
RIGHT('0' + CONVERT(VARCHAR(2), (@sec % 60)), 2)
```
---
Written as a function:
```
CREATE FUNCTION udfTimeSpanFromSeconds(
@se... | If you want you function to return hh:mm:ss then it needs to be as below. This does however limit the total time to be less than 100 hours. You can fix this by increasing the length of the Hours String by changing the right clause and increasing the length of the string returned, as I have now done to illustrate.
(Nor... | How to format time from dd:hh:mm:ss to only hh:mm:ss in SQL server? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
This seems like it would be a question that has been answered a million times before, but searching for a bit only brought up replacing single quotes with double quotes.
The problem is that I have a file with a huge number of single quotes. Is there any way to insert a string as is, without the single quotes throwing ... | If you have a file accessible to the SQL Server, you can read the contents in to a variable with `OPENROWSET`. For example, to read a Unicode text file at `C:\drop\demo.html`:
```
DECLARE @DocumentText nvarchar(MAX);
SELECT @DocumentText = BulkColumn
FROM OPENROWSET(BULK 'C:\drop\demo.html', SINGLE_NCLOB) file;
INSE... | Can you replace the single quotes with two single quotes? That is how SQL Server escapes the single quote in a string.
```
declare @test_string nvarchar(max) = 'string with a single '' quote in it';
print @test_string
string with a single ' quote in it
``` | How to Post a SQL String With Quotes? | [
"",
"sql",
"t-sql",
""
] |
I have query like this:
```
select empid,transDateTime
from Trans_Details
where empId='16510'
and transDateTime >='2015-05-07 00:00:00.000'
and transDateTime< ='2015-05-07 23:59:59.000'
```
I'm getting output like this:
```
empid transDateTime
--------------- -----------------------
16510 201... | This is because `transDateTime` is of `DATETIME` type. On your `WHERE` clause, `2015-05-07` is converted into `DATETIME` and thus results in `2015-05-07 00:00:00.000`.
You can use this instead:
```
WHERE CAST(transDateTime AS DATE) = '20150507'
```
Note that you should use `YYYYMMDD` format for date literals.
---
... | Try this
```
select empid,transDateTime from Trans_Details Td where td.empId='16510'
and convert(date,Td.transDateTime)='2015-05-07'
``` | While filtering date time to date am not getting any result | [
"",
"sql",
"sql-server",
""
] |
I am trying to write a query that would only generate one row per `employerid` instead of generating multiple rows per employer and only filling one of the columns at a time. I am getting the below with my query:

The Query that I am using is this:
... | You can use `GROUP BY` + `MAX` to reduce the results to one line per employee:
```
SELECT Employer.employerid,
max(CASE WHEN Service.xxserviceid = '1' THEN 'Number 1' ELSE 'NULL' END) AS Service1,
max(CASE WHEN Service.xxserviceid = '2' THEN 'Number 2' ELSE 'NULL' END) AS Service2,
max(CASE WHEN Service.xxservi... | ```
SELECT Employer.employerid,
MAX(CASE WHEN Service.xxserviceid = '1' THEN 'Number 1' ELSE 'NULL' END) AS Service1,
MAX(CASE WHEN Service.xxserviceid = '2' THEN 'Number 2' ELSE 'NULL' END) AS Service2,
MAX(CASE WHEN Service.xxserviceid = '3' THEN 'Number 2' ELSE 'NULL' END) AS Service3
FROM Employer
INN... | SQL Server Case Statements | [
"",
"sql",
"sql-server-2014",
""
] |
How do i update table structured like this:
```
id[pkey] | parent_id | position
1 1
2 1
3 1
4 1
5 1
6 2
7 2
8 2
9 2
10 3
11 3
12 3
...and so on
```
to achieve this result:
```
id[pkey] ... | You can get the incremental number using `row_number()`. The question is how to assign it to a particular row. Here is one method using a `join`:
```
update cats
set position = c2.newpos
from (select c2.*, c2.ctid as c_ctid,
row_number() over (partition by c2.parent_id order by NULL) as seqnum... | Try this:
```
UPDATE table_name set table_name.dataID = v_table_name.rn
FROM
(
SELECT row_number() over (partition by your_primaryKey order by your_primaryKey) AS rn, id
FROM table_name
) AS v_table_name
WHERE v_table_name.your_primaryKey = v_table_name.your_primaryKey;
``` | Updating column based on another column's value | [
"",
"sql",
"postgresql",
""
] |
I have a database table populated with 10k rows of data. A great deal of those rows have null values in specific columns. How do I replace this null value with for instance the empty string for a string column?
I'm looking for the *easiest* way to do this since this operation will only need to be performed *once*.
**... | You could try
```
UPDATE tablename set mycolumn = ''
where Id IN (select Id from (select Id from tablename where mycolumn IS NULL) as x)
```
But why do you want to replace `NULL` values with empty strings at all?
If you could disable safe mode [this](https://stackoverflow.com/questions/11448068/mysql-error-code-117... | You can alter the table and set NOT NULL for the columns.
And you can also simply do the following:
> To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect. | How do I remove null from table columns? | [
"",
"mysql",
"sql",
"null",
""
] |
When I design a temporary table as follows, the manager growls at the name *#Temp* and marks it with red highlight.
```
drop table #Temp
select * into #Temp
from Donkeys
```
When I hover over the highlight, the reason is - as expected - that the name isn't recognized.
> Cannot drop the table '#Temp', because it does... | It can be achieved by the combination `ctrl``shift``R`.
You are receiving this issue because #temp does not exist yet. You either need to check for it's existence like so:
```
if OBJECT_ID('tempdb..#temp') is not null
begin
drop table #temp
end
select * into #Temp
from Donkeys
```
or you can just drop the table afte... | use like this way :-
```
If Object_Id('tempdb.dbo.#Temp') Is Not Null Drop Table #Temp;
select * into #Temp
from Donkeys
``` | How to calm the IDE about not declared temporary table? | [
"",
"sql",
"sql-server",
"ide",
""
] |
I have an EmpName Table.
`Select * from EmpName`
```
NameID FirstName MiddleName LastName
1 Sam NULL NULL
2 NULL Todd Tarzan
3 NULL NULL Sare
4 Ben Parker NULL
5 James Nick Nancy
```
Now I write the following query to get the fu... | When you concatenate strings, `NULL` takes precedence. So, use `COALESCE()`. This is a pain with separators, but the following should do what you want:
```
Select ltrim(coalesce(' ' + FirstName, '') +
coalesce(' ' + MiddleName, '') +
coalesce(' ' + LastName)
) as FullName
From Emp... | when you try to concate string with **NULL** it always give null
```
Select isnull(FirstName,'') + ' ' + isnull(MiddleName,'') + ' ' + isnull(LastName,'')
As FullName from EmpName
```
if you use sql server 2012 or later version
```
Select concat(FirstName,MiddleName,LastName) as FullName
As FullName from EmpName
`... | Sql Query to get the Full name from the table Employee Eliminating Null Value | [
"",
"sql",
"sql-server",
""
] |
I am using SQL Server 2012. I have a table which contains a column `MyCol` which can only be the four values below:
```
MN
ABB
BO
BN
```
When I query the data from my table I want to change these values to a numeric value instead, so say MN = 1, ABB = 2, BO = 3 & BN = 4.
How do I do this using a select statement? | Simple `CASE` statement will do:
```
SELECT
CASE MyCol
WHEN 'MN' THEN 1
WHEN 'ABB' THEN 2
WHEN 'BO' THEN 3
WHEN 'BN' THEN 4
END
FROM
dbo.Yourtable
``` | ```
SELECT
Case When MyCol = 'MN' Then 1
WHEN MyCol = 'ABB' Then 2
When MyCol = 'BO' Then 3
When MyCol = 'BN' Then 4 End as MyCol
From MyTable
``` | Query a column and change value to numeric value | [
"",
"sql",
"sql-server",
""
] |
I have the below structure(`' '` refers to empty spaces):
```
name description
---------------------
a yes
b ' '
c ' '
d null
```
I am searching for a query that give me the rows contain empty spaces, asked for the below result .
```
name description
--------------------... | You can user [REGEXP\_LIKE](http://docs.oracle.com/cd/B12037_01/server.101/b10759/conditions018.htm):
```
with src as (select 'a' as name,'yes' as description from dual
union all
select 'b',' ' from dual
union all
select 'c',' ' from dual
union all
select 'd',null from dual)
select * from src where regexp_like(... | Use TRIM function to trim the spaces.
```
select * from tab1 where TRIM(description) IS NULL;
```
I have not tested it but it should work. | how to get columns have long spaces ( multiple spaces) | [
"",
"sql",
"oracle",
""
] |
Assuming t is a large table, and the following two queries
```
SELECT t1.value, t2.value
FROM t as t1 JOIN t as t2
ON t1.id = t2.id
WHERE t1.key = '123'
```
and
```
SELECT t1.value, t2.value
FROM t as t1 JOIN t as t2 JOIN t as t3
ON t1.id = t2.id
WHERE t1.key = '123'
```
the second one having a JOIN with a table... | Your second query doesn't have an `ON` clause for the second join:
```
SELECT t1.value, t2.value
FROM t as t1
JOIN t as t2
JOIN t as t3 ON t1.id = t2.id
WHERE t1.key = '123';
```
This means that every matching record in t1 will be joined onto every record in t2. This is, perhaps, what you meant:
```
SELECT t1.val... | It is not that the MySQL optimizer isn't smart enough to remove the unused query, it is just that you are using the wrong syntax here. As the documentation states, your query will be performed as:
```
JOIN t as t2 JOIN t as t3 --> t2 CROSS JOIN t3
```
The syntax you are using isn't standard SQL and cannot be used in ... | MySQL: join with an unused table increases execution time? | [
"",
"mysql",
"sql",
""
] |
I have the sql using Oracle SQL Developer below that works, but I am concerned about performance over a larger live database.
Please excuse all the join tables, this is showing the connections to the \_aud table and revision\_table that keeps the audit history.
```
select cust.forename, cust.surname
from customer cus... | I tried the solutions posted here and they all seem to work, many thanks for the responses - I hadn't investigated the having clause before.
I added any required indexes and ran explain plans on all the options, my original query had the lowest cost. So I think I will use that option moving forward. | Are you sure you need all those joins?
The same query with different WHERE-conditions usually translates to a CASE:
```
select cust.forename, cust.surname
from customer cust
where
-- this value is substituted programatically
sd.type = 5
and exists
( select *
from
customer cust_tmp1
join section_detail... | Optimising SQL sub query in where clause | [
"",
"sql",
"oracle",
"oracle11g",
"query-optimization",
""
] |
I have values being returned with 255 comma separated values. Is there an easy way to split those into columns without having 255 substr?
```
ROW | VAL
-----------
1 | 1.25, 3.87, 2, ...
2 | 5, 4, 3.3, ....
```
to
```
ROW | VAL | VAL | VAL ...
---------------------
1 |1.25 |3.87 | 2 ...
2 | 5 | ... | You can use `regexp_substr()`:
```
select regexp_substr(val, '[^,]+', 1, 1) as val1,
regexp_substr(val, '[^,]+', 1, 2) as val2,
regexp_substr(val, '[^,]+', 1, 3) as val3,
. . .
```
I would suggest that you generate a column of 255 numbers in Excel (or another spreadsheet), and use the spreadsh... | Beware! The regexp\_substr expression of the format `'[^,]+'` will not return the expected value if there is a null element in the list and you want that item or one after it. Consider this example where the 4th element is NULL and I want the 5th element and thus expect the '5' to be returned:
```
SQL> select regexp_s... | Split comma separated values to columns in Oracle | [
"",
"sql",
"oracle",
"split",
""
] |
I need to calculate how many orderlines there are based on the orderlineNo being distinct. Each OrderNo is different BUT the OrderLineNo is the same for each order.
i.e. 9 lines on a order then order lines number will go from 1 - 9. The same if on another order there are 3 orderlines they will go from 1 - 3
But in ord... | You can add DISTINCT to a COUNT:
```
select OrderNo, count(distinct OrderLineNo)
from tab
group by OrderNo;
```
Or if OrderLineNo always starts with 1 and increases without gaps:
```
select OrderNo, max(OrderLineNo)
from tab
group by OrderNo;
```
Edit:
Based on the comment it's not a count per OrderNo, but a globa... | I guess you want this:
```
SELECT OrderNo, COUNT(distinct OrderLineNo) as CntDistOrderLineNoPerOrderNo
FROM Table1
GROUP BY OrderNo
```
`demo`
So for every `OrderNo` the count of dictinct `OrderLineNo` which is 7 for 987654.
If you instead want the sum of all distinct OrderLineNo as commented.
```
WITH CTE AS
(
... | Counting Values based on distinct values from another Column | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
Please take a look at the below sql fiddle.
<http://sqlfiddle.com/#!6/26b91/1>
[Latest SQL Fiddle is here](http://sqlfiddle.com/#!6/b1e79/2)
I will try to describe the output I require first. I am expecting two rows since there are two conditions in the `PullPointDate` table. The multiple rows that are in the `PullP... | In addition to Vladimir Baranov's answer you can also use the CTE with Row\_Number:
[SQLFiddler](http://sqlfiddle.com/#!6/b1e79/19/0)
```
WITH CTE
AS
(
SELECT ROW_NUMBER () OVER (PARTITION BY
P.BatchCode ORDER BY P.AuditNumber Desc) RN ,
P.StudyCode , P.BatchCode ,
PP.condNumber ,P.pu... | This appears to give me what I desire...
SELECT o.\*
FROM pullpoint o
LEFT JOIN pullpoint b
ON o.studyCode = b.studyCode
and o.batchCode = b.batchcode
AND o.auditNumber < b.AuditNumber
WHERE b.AuditNumber is NULL
I am sure I will get to work tomorrow and the thing will not work though :( | Select latest row value for multiple rows | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
I have a problem in Oracle SQL that I'm trying to get my head around.
I'll illustrate with an example. I have three tables that I am querying:
```
Employees
__________________________________________
| EmployeeID | Name |
| 1 | John Smith |
| 2 | Douglas Hoppalot ... | You should use subqueries on int and ext to do the summing, and join to the subqueries.
I also suggest using explicit JOINs rather than table, table, table
e.g.
```
SELECT emp.Name, int.Amount AS InternalCostTotal, ext.Amount AS ExternalCostTotal
FROM Employees emp
JOIN (
SELECT EmployeeID, SUM(Amount) AS Amoun... | [SQL Fiddle](http://sqlfiddle.com/#!4/827e9/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE Employees ( EmployeeID, Name ) AS
SELECT 1, 'John Smith' FROM DUAL
UNION ALL SELECT 2, 'Douglas Hoppalot' FROM DUAL
UNION ALL SELECT 3, 'Harry Holiday' FROM DUAL;
CREATE TABLE InternalCosts ( IntID, Amount, Empl... | SQL SELECT Sum values without including duplicates | [
"",
"sql",
"oracle",
"select",
"group-by",
"sum",
""
] |
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it.
Ex:
```
Declare @date datetime
Declare @time time
```
I want something like this
```
@date = @date + @time (but not concatenation)
SEL... | You can tranform your time to seconds and add them to your datetime value:
```
DECLARE @datetime DATETIME = GETDATE(),
@time TIME = '01:16:24',
@timeinseconds INT
PRINT 'we add ' + CAST(@time AS VARCHAR(8)) + ' to ' + CONVERT(VARCHAR,@datetime,120)+ ':'
SELECT @timeinseconds = DATEPART(SECOND, @time... | The only thing you are missing is that @time needs to be cast back to a datetime before adding to @date.
```
declare @date datetime = '2022-05-26'
declare @time time = '09:52:14'
declare @Startdate datetime
set @date = @date + convert(datetime,@time)
SELECT @Startdate = DATEADD(DAY, -1, @date)
```
Produces:
[![ente... | How to add date and time in SQL Server | [
"",
"sql",
"sql-server",
""
] |
Hard to make a good title for this (feel free to edit), but hope it will make more sense ..
Say I have the following tables:
t1:
```
i1 v1
_________
1 bob
2 NULL
3 sam
4 NULL
5 kenny
5 NULL
```
t2:
```
i2 v2 item
______________
1 bob prod_1
2 nick prod_2
... | Your query is fine, although I would use `NOT EXISTS`:
```
SELECT dm2.*
FROM web.delete_me2 dm2
WHERE NOT EXISTS (SELECT 1
FROM web.delete_me1 dm1
WHERE dm2.some_int2 = dm1.some_int1 and dm2.some_var2 = dm1.some_var1
);
```
Although you can write this as a `join`... | ```
SELECT DISTINCT T1.*, T2.*
FROM T1
JOIN T2
ON T1.ID = T2.ID
LEFT JOIN T2 AS T2NO
ON T2NO.NAME = T1.NAME
WHERE T2NO.NAME IS NULL
```
or try this
```
SELECT DISTINCT T2.*
FROM T2
JOIN T1
ON T1.ID = T2.ID
LEFT JOIN T1 AS T1NO
ON T1NO.NAME = T2.NAME
WHERE T1NO.NAME IS NULL
``` | Query a table using conditions with another table | [
"",
"sql",
"sql-server",
"t-sql",
"join",
""
] |
I try to get a query without parameters to obtain the list of dates from the current month.
Something like this:
> SYSDATE = 16/07/15
I want the next list:
> 01/07/15
> 02/07/15
> ...
> 30/07/15
> 31/07/15 | Here's what I got to work:
```
SELECT TRUNC(SYSDATE, 'MM') + LEVEL - 1 AS day
FROM dual
CONNECT BY TRUNC(TRUNC(SYSDATE, 'MM') + LEVEL - 1, 'MM') = TRUNC(SYSDATE, 'MM')
;
```
The key in this query is `TRUNC(SYSDATE, 'MONTH')` which is the first day of the current month.
We use hierarchical queries to keep adding one... | Selects all the days for current month
```
SELECT TO_CHAR (TRUNC (SYSDATE, 'MM'), 'YYYYMMDD')+(LEVEL - 1) each_date
FROM DUAL a
CONNECT BY LEVEL < (TO_NUMBER (TO_CHAR (TRUNC (SYSDATE, 'MM') - 1, 'DD'))+1)
``` | How do I get all dates from sysdate's month with Oracle SQL? | [
"",
"sql",
"oracle",
""
] |
I am dealing with tables which (for the purposes of displaying here) look like the following:
A
```
A_ID | Clob_Col
1 | value
2 | value
3 | null
4 | value
5 | null
6 | value
7 | value
8 | null ... | I think this does what you're after:
```
with a as (select 1 a_id, 'val1' clob_col from dual union all
select 2 a_id, 'val2' clob_col from dual union all
select 3 a_id, null clob_col from dual union all
select 4 a_id, 'val4' clob_col from dual union all
select 5 a_id, null c... | I think you forgot to use "on" clause for join. You can try this :
```
SELECT a.A_ID, a.Clob_Col, b.B_ID, c.C_ID
from A a
LEFT JOIN B b on a.A_ID=b.A_ID
LEFT JOIN C c on b.C_ID=c.C_ID
WHERE a.A_ID between 2 and 7
AND c.C_ID NOT IN (22, 23, 24)
```
Hope it will work. | Oracle sql query | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
A database table can only have one primary key not two or more .. why is that so? | The major reason is because that is the definition of the primary key. A table can have multiple unique keys that identify each row, but only one primary key.
In databases such as MySQL, the primary key is also a clustered index. That provides a more direct reason. The data is sorted on the pages according to the clus... | A (relational) table's "superkeys" are the sets of columns for which each row has a subrow unique in the table. (Note that every superset of a superkey is a superkey too.) (What unadorned SQL `KEY` declares, and supersets of those.) A superkey that contains no smaller superkey is a "candidate key". Normalization and ot... | Why can a database table have only one primary key? | [
"",
"mysql",
"sql",
"database",
"oracle",
""
] |
I got a value in a field called it (EmployeeDetailKey - varchar(10)) with sequential values such as
> 00001, 00002, 00003....
It is in a table Employeedetail. When ever a new Employee detail has to be inserted I have to get the max(EmployeeDetailKey) and increment by 1 and store it back. If I have 10 employeedetail r... | If you prefer a solution without changing the table structure, then:
1. Cast your zero-padded string value to int. This is easy in SQl server, as it will easily convert such strings to numbers:
`SELECT CAST('00003' AS int)`
This will return integer value of 3.
2. Find MAX()
Just perform `MAX()` on column y... | Just add an identity column to your table. I would suggest something like:
```
IntEmployeeDetailKey int not null identity(1, 1) primary key,
. . .
```
Then add a computed column:
```
EmployeeDetailKey as (right(('00000' + cast(IntEmployeeDetailKey as varchar(10)), 5)
```
Then SQL Server will do the incrementing aut... | Reg: Auto incrementing a value in SQL Table | [
"",
"sql",
"sql-server",
"auto-increment",
""
] |
I have searched a lot, but most of solutions are for concatenation option and not what I really want.
I have a table called `X` (in a Postgres database):
```
anm_id anm_category anm_sales
1 a_dog 100
2 b_dog 50
3 c_dog 60
4 a_cat 70
5 b_cat 80
6 ... | Use `case` statement to group the animals of same categories together
```
SELECT CASE
WHEN anm_category LIKE '%dog' THEN 'Dogs'
WHEN anm_category LIKE '%cat' THEN 'cats'
ELSE 'Others'
END AS Animals_category,
Sum(anm_sales) AS total_sales
FROM yourtables
GRO... | By using **PostgreSQL's** [**split\_part()**](http://www.postgresql.org/docs/current/interactive/functions-string.html)
```
select animal||'s' animal_cat,count(*) total_sales,sum(anm_sales) sales_sum from(
select split_part(anm_cat,'_',2) animal,anm_sales from x
)t
group by animal
```
[**sqlfiddle**](http://sqlfiddl... | Group rows with similar strings | [
"",
"sql",
"postgresql",
"aggregate",
""
] |
I'm having a difficult time writing a query for a personal project. I have some data for a housing community that lists all the historical statuses of each unit. Each status, uniquely defined by the column "HMY", represents a period of time that a resident stayed in the unit. You can see in dtStart when a resident bega... | ```
WITH t1 (property, hunit) AS
(
SELECT DISTINCT
property,
hunit
FROM table
)
SELECT
t1.property,
t1.hunit,
highest.hmy,
highest.dtstart,
highest.dtend
FROM t1
CROSS APPLY
(
SELECT TOP(1)
hmy,
dtstart,
dtend
FROM table t
WHERE
t.property = t1.property
AND t.hunit = t1... | You could use ROW\_NUMBER() to partition by hUnit and order by hMy in descending order. Then just select the first row, which contains the highest hMy, from each partition.
```
SELECT hMy,Property,hUnit,dtStart,dtEnd
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY hUnit ORDER BY hMy DESC) RowID,hMy,Property,hUnit,dtS... | Group by unit and show the unit that has the most recent date | [
"",
"sql",
"sql-server",
"group-by",
""
] |
The code below is correct as it show me
```
SELECT TOP 3 P.CategoryID,SUM(OD.Quantity) From "Order Details" AS OD
INNER JOIN
Products AS P
ON OD.ProductID=P.ProductID
GROUP BY P.CategoryID
ORDER BY SUM(OD.Quantity) DESC
```
The result is
```
CategoryID su... | MySQL uses LIMIT, not TOP. This Issue is tagged with MySQL, not SQL Server, so I'm answering accordingly.
```
SELECT
P.CategoryID, SUM( OD.Quantity )
FROM
OrderDetails AS OD
INNER JOIN Products AS P
ON OD.ProductID=P.ProductID
GROUP BY
P.CategoryID
ORDER BY
SUM( OD.Quantity ) DESC
LIMIT 3;
```
In the sp... | You should not select SUM(OD.Quantity) in the inner query.
```
SELECT CategoryName FROM Categories WHERE CategoryID IN
(
SELECT TOP 3 P.CategoryID From "Order Details" AS OD
INNER JOIN
Products AS P
ON OD.ProductID=P.ProductID
GROUP BY P.Categ... | Subquery Executing Problems | [
"",
"sql",
""
] |
I have a dynamic SQL query
```
DECLARE @ItemAreaCode NVARCHAR(MAX) = 'A062',
@SQLStringDropTable NVARCHAR(MAX);
SET @SQLStringDropTable= 'DROP TABLE' + ' ' +
'[@ItemAreaCode].[ChangedRMAllocation]'
PRINT @ItemAreaCode
EXEC sp_executesql @SQLStringDropTable , N'@ItemAreaCode NVARCHAR... | You probably meant to expand the variable:
```
DECLARE @ItemAreaCode sysname = 'A062',
@SQLStringDropTable NVARCHAR(MAX);
SET @SQLStringDropTable =
'DROP TABLE ' + quotename(@ItemAreaCode) + '.[ChangedRMAllocation]';
EXEC (@SQLStringDropTable);
``` | You are setting you parameter as a string within the dynamic SQL.
`@ItemAreaCode` should not be included.
This should work :
```
DECLARE @ItemAreaCode NVARCHAR(MAX) = 'A062',
@SQLStringDropTable NVARCHAR(MAX);
SET @SQLStringDropTable= 'DROP TABLE' + ' ['
+ @ItemAreaCode + '].[Change... | SQL Server Dynamic SQL Execution | [
"",
"sql",
"sql-server",
"dynamic-sql",
""
] |
I am trying to get the data associated with the most recent `curve_date` corresponding to each `tenor_years` value and am using the query below to do this. However, I am not getting the data as I would like it to be.
```
SELECT
tenor_years,
yield_pct,
MAX(curve_date) AS "MostRecentDate"
FROM yc_node_hist
where f... | SQL Server offers `PARTITION`/`OVER` functionality for situations like that.
```
SELECT tenor_years,
yield_pct,
MostRecentDate
FROM (
SELECT
tenor_years,
yield_pct,
curve_date AS "MostRecentDate",
RANK() OVER (PARTITION BY tenor_years ORDER BY curve_date DESC) N
... | You have to remove the yield\_pct from the group by:
```
SELECT
tenor_years,
MAX(curve_date) AS "MostRecentDate"
FROM yc_node_hist
where fk_yc_update = 12
GROUP BY tenor_years;
```
And then join back on itself:
```
SELECT a.tenor_years, a.curve_date,a.yield_pct
FROM yc_node_hist a
INNER JOIN (
SELECT
tenor... | Getting the most recent data for each value in another column | [
"",
"sql",
"sql-server",
""
] |
Is there any possible way to execute something like this in T-SQL?
```
CASE @@VERSION
WHEN 'SQL Server 2005'
THEN Command_A
ELSE Command_B
END
```
This case block should pick Command\_A if the server version is 2005. If not Command\_B should get executed. | Actually the case is a "subcommand" of SELECT
you could achieve what you want with something like this:
```
declare @s varchar(255)
select @s = case @@VERSION
when 'SQL Server 2005'
THEN 'command 1'
ELSE 'command 2'
END
exec (@s)
``` | You can use this `CASE` to get the sql-server version:
```
SELECT CASE SUBSTRING(CAST(SERVERPROPERTY('productversion')AS nvarchar(128)), 1, CHARINDEX('.', CAST(SERVERPROPERTY('productversion')AS nvarchar(128))) - 1)
WHEN 7 THEN 'SQL Server 7'
WHEN 8 THEN 'SQL Server 2000'
WHEN 9 THEN 'SQL Server 2... | T-SQL: Execute command in case block | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In my MySQL database, I have a table with different questions in different categories.
I would like to write a SQL statement that returns 3 RANDOM questions of EACH category.
**Here is an example of database records:**
```
id question category
1 Question A 1
2 Question B 1
3 Question C 1
4 Question D ... | Yes, you can do this by enumerating the rows and then fetching the top three:
```
select r.id, r.question, r.category
from (select r.*,
(@rn := if(@c = category, @rn + 1,
if(@c := category, 1, 1)
)
) as seqnum
from `random` r cross join
... | In addition to the other answer, this is also another way to do it.
```
SELECT r.* FROM random r
WHERE (
SELECT COUNT(*) FROM random r1
WHERE r.category = r1.category AND r.id < r1.id
) <= 2
ORDER BY r.category ASC, RAND()
``` | How to get RANDOM records from each category in MySQL? | [
"",
"mysql",
"sql",
""
] |
I have this table structure:
```
TABLE: PERSON TABLE: CAR
PersonID PersonID | CarID
------ ---------|---------
1 1 | 51
1 | 52
TABLE: PET TABLE: AGE
PersonID | PetID Person | AgeID
---------|---- -------|----
1 | 81 ... | [SQL Fiddle](http://sqlfiddle.com/#!3/f584a/45)
**Query 1**:
```
SELECT p.PersonID,
( SELECT COUNT(1) FROM CAR c WHERE c.PersonID = p.PersonID ) AS Cars,
( SELECT COUNT(1) FROM PET t WHERE t.PersonID = p.PersonID ) AS Pets,
a.AgeID AS Age
FROM PERSON p
LEFT OUTER JOIN
AGE a
... | Should work with duplicate `Petid` or duplicate `carid`
[**SqlFiddle Demo**](http://sqlfiddle.com/#!3/f584a/37)
```
WITH person_cte
AS (SELECT *
FROM person),
car_count
AS (SELECT Count(1) AS car,
p.personid
FROM person_cte p
LEFT OUTER JOIN ... | How to use UNION with COUNT | [
"",
"sql",
"oracle",
""
] |
I've read about this problem on a few different sites, but I still don't understand the solution.
From what I understand, SQL will optimize the query in the function and sometimes the Order By clause will be ignored. How can you sort results?
How can I sort results in a simple table valued function like this?
```
Cre... | The `order by` needs to be in the statement that selects from the function.
```
SELECT CompetitionId
FROM [dbo].fTest()
ORDER BY CompetitionId
```
This is the only way to get reliable results that are assured to [not suddenly break in the future](https://stackoverflow.com/a/11231935/73226). | This is just a bit of an ingenious workaround and only useful in some scenarios but it worked beautiful for what I needed: you can create a stored procedure that does a `select *` from the function with the desired order by clause and use that instead... | Order By In a SQL Table Valued Function | [
"",
"sql",
"sql-server",
""
] |
I want to find a word in a string with SQL. I currently use:
```
SELECT * FROM dreams
WHERE
title
LIKE '%lo%'
```
But I want also to find other spellings like "Lo" or "LO" and so on..
Any Ideas ? | Convert it to upper case before comparing
```
SELECT * FROM dreams
WHERE
upper(title)
LIKE '%LO%'
``` | ```
SELECT * FROM dreams WHERE title LIKE '%lo%'
union
SELECT * FROM dreams WHERE title LIKE '%LO%'
union
SELECT * FROM dreams WHERE title LIKE '%Lo%';
``` | SQL find Word in String (any Spelling) | [
"",
"sql",
""
] |
I have a log with fingerprint timestamps as follows:
```
Usr TimeStamp
-------------------------
1 2015-07-01 08:01:00
2 2015-07-01 08:05:00
3 2015-07-01 08:07:00
1 2015-07-01 10:05:00
3 2015-07-01 11:00:00
1 2015-07-01 12:01:00
2 2015-07-01 13:03:00
2 2015-07-01 14:02:00
1 2015-0... | Here is my final working code:
```
create table tsts(id int, dates datetime)
insert tsts values
(1 , '2015-07-01 08:01:00'),
(2 , '2015-07-01 08:05:00'),
(3 , '2015-07-01 08:07:00'),
(1 , '2015-07-01 10:05:00'),
(3 , '2015-07-01 11:00:00'),
(1 , '2015-07-01 12:01:00'),
(2 , '2015-07-01 13:03:00'),
(2 , ... | To start with you can use datepart to get hours for the days as following and then use group by user
```
SELECT DATEPART(HOUR, GETDATE());
```
[**SQL Fiddle**](http://sqlfiddle.com/#!3/04e00/1)
```
SELECT Convert(varchar(5),DATEPART(HOUR, timestamp)) + ':00' as time,
count(usr) as users
from tbl
group by DATEPART(HO... | SQL TSQL for Workers per Hour | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2014-express",
""
] |
I have a table called `quiz` and it has 3 columns:
```
enterYear enterMonth quizMark
2013 7 9.5
2013 8 8.5
2013 9 9.75
2013 10 10
2013 11 7.75
2013 12 8.5
2014 1 5
2014 ... | ```
select * from quiz q where q.year>2013 or(q.year=2013 and q.month>=9)
``` | ```
select * from quiz q where (q.year>=2013 and q.month>=9) OR q.year>=2014
```
This will capture all your dates from September 2013 upwards. | SQL - select data that have dates greater than a month in a year | [
"",
"sql",
"sql-server",
""
] |
I am using Oracle SQL. Why is this insert statement throwing an expression missing error?
```
INSERT INTO T_DATA(id, object_type, object_id,
measurement_id, derived_ind, no_hist_ind,
display_order, stored_precision, display_precision,
required... | Your usage can be just `INSERT.. INTO.. SELECT..`
```
INSERT INTO T_DATA(id, object_type, object_id,
measurement_id, derived_ind, no_hist_ind,
display_order, stored_precision, display_precision,
required_ind, mod_user, mod_dtime)
... | Just as an alternative to MahMaheswaran's answer. You can still achieve the query whilst using VALUES. You just needed to wrap the SELECT statement in parenthesis.
```
INSERT INTO T_DATA (Id,
object_type,
object_id,
measurement_id,
derived_ind,
no_hist_ind,
display_order,
stored_precision,
... | Why is this insert statement throwing an expression missing error? | [
"",
"sql",
"oracle",
"sql-insert",
""
] |
I have a database like the following:
```
id | col_1 | col_2
------------------
1 | a | x
2 | a | x
3 | b | x
4 | b | z
5 | c | x
```
I'm trying to get all rows that match col\_2 = x plus the frequency of col\_1, ordered by the frequency. For example, the output would be:
```
id | ... | Your `freq` column looks like an independent, table-wide count of rows where `col_2 = 'x'`, grouped by `id`. You can get that using this query:
Here is SQL FIDDLE [DEMO](http://sqlfiddle.com/#!9/7358e/4)
```
SELECT
col_1,
COUNT(*) AS freq
FROM myTable
WHERE col_2 = 'x'
GROUP BY col_1
```
Join it to a query for i... | This is @EdGibbs solution rewritten using a Scalar Subquery. MySQL creates a different plan, you should test which is more efficient ([fiddle](http://sqlfiddle.com/#!9/2dbf1/1)):
```
SELECT
id,
col_1,
col_2,
(SELECT COUNT(*)
FROM myTable AS t2
WHERE t.col_1 = t2.col_1
AND col_2 = 'x') AS freq
FROM m... | How to get all rows when using GROUP BY? | [
"",
"mysql",
"sql",
""
] |
I have a users, questions and answers table, What I wish to do is select from questions and users table based on their which is their username and then count the number of rows in the answers table based on the relationship between the questions and answers table. Bear in mind the current state of the tables are :
> Q... | There are a few issues with your query. First, the presence of `COUNT()` makes the query into an aggregate query. Without `GROUP BY`, aggregate queries can't generate more than a single row.
Another issue: you've got some JOIN confusion with USERLOG. Hopefully there's only one row in USERLOG for each user, or you may ... | Try this:
```
SELECT questions.question_id,
questions.username,
questions.question,
userlog.user_mail,
(Select COUNT(answers.answer) where answers.question_id = questions.question_id) as answerCount
FROM questions
INNER JOIN userlog ON userlog.username... | Selecting from two tables and counting a third | [
"",
"mysql",
"sql",
"database",
"mysql-workbench",
""
] |
Hello I'm currently in a Intro to SQL in college. We are using Murach SQL Sever 2012 for Developers. I'm currently in Chapter 4 and I'm not understanding what a Join Condition is. I understand that is indicates how two tables should be compared, but what I can't understand is the syntax.
```
SELECT InvoiceNumber, Vend... | Implement the join condition in sql by a linq query:
```
var result =(from e in employee
join v in vendor where e.EmployeeId equals v.EmployeeId
select new
{
EmployeeName = e.employeeName,
EmployeeSalary =e.employeeSalary,
... | Join clause combines records from two or more tables in a relational database.
**Example:**
If you have two table called `Vendors` and `Invoices`. Now, you are looking for common data between both table on the basis of id i.e. `VendorId`.
But, first of all, you need to access column of a table. So, you need to speci... | Join Conditions in SQL | [
"",
"sql",
"join",
"conditional-statements",
""
] |
I have a table:
```
year val
---- ----
2013 4
2014 6
2014 2
2014 6
2015 1
2015 3
2016 7
```
is there a way to get the sum of the previous years for every year in the table?
the result should be like this:
```
2013 0
2014 4
2015 18
2016 22
2017 29
```
I tried something like this:
... | If you want old years only then use this query
```
SELECT DISTINCT year , ( SELECT SUM(val) FROM table as temp2 WHERE temp2.year < temp1.year ) as v FROM table as temp1
```
If you want to include year too then change temp2.year < temp1.year to <= , if you want to filter by years , then use comparison =
so
```
SELEC... | Your question is a bit challenging because you want `0` for the first year:
```
select year,
( (@p := @p + sumval) - sumval) as cumeprev
from (select year, sum(val) as sumval
from table t
group by year
) t cross join
(select @p := 0) params
order by year;
``` | SQL sum of previous entries | [
"",
"mysql",
"sql",
"sum",
""
] |
I need to get the Supplier ID from the SQL Select statement inside Case statement. Once I put the `A.SUPPLIER_ID` to Select Statement I get an Error. How to do this?
```
Select
CASE
WHEN TYPE = 1 THEN
(
SELECT A.name
from BIZZXE_V2_SCH.SUPPLIERS A
... | You can't put complete queries into a `case` statement. But this should work
```
SELECT name
from BIZZXE_V2_SCH.SUPPLIERS
where SUPPLIER_ID = 30 and TYPE = 1
union all
SELECT name
from BIZZXE_V2_SCH.STOCK_SUPPLIER
where SUPPLIER_ID = 31 and TYPE <> 1
``` | You should be able to handle this in your WHERE statement, like this.
```
SELECT A.name
FROM BIZZXE_V2_SCH.STOCK_SUPPLIER A
WHERE (A.SUPPLIER_ID = 30 AND TYPE = 1) OR
A.SUPPLIER_ID = 31
``` | Sql Case Statement Error Cannot select More Than one Column | [
"",
"sql",
"oracle",
"case",
"oracle-apex",
""
] |
Untested waters,I'm trying to find a way to ease things up. Instead of having a nested select in a cursor in PL-SQL. I'm trying to make a case when in the cursor. Since the cursor can have different inparameters and I need to sort things accordingly.
Is this possible? My code looks like this. It's easy to read ao\_in ... | What you want could be done with the [OPEN-FOR](http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems033.htm) statement, like this:
```
PROCEDURE theProcedure (ao_in IN VARCHAR2)
TYPE t_cur IS REF CURSOR;
order_cur t_cur;
begin
Case when ao_in = 'NIEC'
then
open order_cur for
... | Assuming that you have a column called "ao\_in" in your eh\_order\_t@ngext\_dblink table, I think what you're after is something like this:
```
PROCEDURE theProcedure (p_ao_in IN VARCHAR2)
IS
CURSOR order_cur
IS
SELECT t1.nr,
t1.status$nr
FROM eh_order_t@NGEXT_DBLINK t1
WHERE t1.status$nr... | Case when in Cursor | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have table called PhoneNumbers with columns Phone and Range as below

here in the phone column i have a phone numbers and in range column i have a range of values i need the phone numbers to be included.For the first phone number 9125678463 I need ... | I have a solution which goes a classic way BUT: it does not need recursions and it does not need any loops! And it works even if your range has length of 3 or 5, or whatever...
first i create a table with numbers (from 1 to 1 million in this example - you can adopt this in TOP () clause):
```
SELECT TOP (1000000) n =... | You can use CTE like this:
```
;WITH CTE (PhoneNumbers, [Range], i) AS (
SELECT CAST(Phone AS bigint), [Range], CAST(1 AS bigint)
FROM yourTable
UNION ALL
SELECT CAST(PhoneNumbers + 1 AS bigint), [Range], i + 1
FROM CTE
WHERE (PhoneNumbers + 1) % 10000 <= [Range]
)
SELECT PhoneNumbers
FROM CTE... | SQL to get sequence of phone numbers | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a Data as follows:
```
Order_id Created_on Comment
1 20-07-2015 18:35 Order Placed by User
1 20-07-2015 18:45 Order Reviewed by the Agent
1 20-07-2015 18:50 Order Dispatched
2 20-07-2015 18:36 ... | SQL is about horizontal relations - vertical relations do not exist. To a relational database they're just 2 rows, stored somewhere on a disk, and until you apply ordering to a result set the 'first and second' are just 2 randomly picked rows.
In specific cases it's possible to calculate the time difference within SQL... | I think you can use a query like this:
```
SELECT t1.Order_id, t1.Created_on, TIMEDIFF(mi, t1.Created_on, COALESCE(MIN(t2.Created_on), t1.Created_on)) AS toNextTime
FROM yourTable t1
LEFT JOIN yourTable t2 ON t1.Order_id = t2.Order_id AND t1.Created_on < t2.Created_on
GROUP BY t1.Order_id, t1.Created_on
``` | Calculate difference in Dates for each cell with next cell | [
"",
"mysql",
"sql",
"date",
"difference",
""
] |
Say I have the following rows
```
DATE
2016-04
2015-11
2009-08
```
And I want them to appear like this, with the date always set to the first of the month
```
DATE
01-APR-2016
01-NOV-2015
01-AUG-2009
``` | You need to first convert your "month date" into a real date using `to_date()`:
```
to_date(the_column||'-01', 'yyyy-mm-dd')
```
Note that you need to add a day (`||'-01'`) in order to have a valid input for the `to_date()` function.
and then you can format the resulting date as you like using `to_char()`
```
selec... | to answer your immediate question:
```
drop table junk;
create table junk ( notadate varchar2(7) );
insert into junk values ( '2016-04' );
insert into junk values ( '2015-11' );
insert into junk values ( '2009-08' );
commit;
alter session set nls_date_format='dd-mon-yyyy';
select to_date(notadate... | Oracle SQL | How would I change a text field to a date field with a specific format? | [
"",
"sql",
"oracle",
"date",
""
] |
When executing any one of the following commands:
```
osql -E -S ComputerName\InstanceName
osql -E -S ComputerName\InstanceName -i MyScript.sql -o MyOutput.rpt
osql -E -q "SELECT * FROM Northwind.dbo.Shippers"
osql -E -Q "SELECT * FROM Northwind.dbo.Shippers" -o MyOutput.rpt
```
I am getting the following error:
```... | Do you have your logged in account set up as a user in SQL Server?
I usually work with specific accounts and SQL Server logins instead of Trusted Logins, and then just specify the database coordinates on the command line with the -S, -D, -U, and -P options:
```
osql -S %SERVERNAME% -U %USERNAME% -P %PASSWORD% -d %DBN... | You have to run all command in a single line
like this
```
osql -E -S ComputerName\InstanceName -i MyScript.sql -o MyOutput.rpt
```
or
`osql -E -S ComputerName\InstanceName -Q "SELECT * FROM Northwind.dbo.Shippers" -o MyOutput.rpt`
Now you have to see if you can log in SQL Server or if the service is up or even if ... | Running queries using osql | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"osql",
""
] |
please help,
this is my table
```
date column1 column2 trx
2015-07-01 **side1 Internet** 777903315
2015-07-01 **side1 Internet** 41426210
2015-07-01 side1 Unlimited 2263500
2015-07-01 side1 Business 427000
2015-07-01 side1 Extreme 3540900
... | ```
SELECT t.date, t.c1, t.c2, t.trx
, CASE WHEN t.trx = m.trx THEN 'pre' ELSE 'post' END AS `type`
FROM so_q31531850 t
LEFT OUTER JOIN ( SELECT DATE, c1, c2, MAX(trx) AS trx FROM so_q31531850 GROUP BY 1,2,3) m
ON m.trx = t.trx AND m.c1 = t.c1 AND m.c2 = t.c2 AND m.date = t.date
```
Please not... | You can use the following query:
```
SELECT m.*,
CASE trx
WHEN mintrx THEN 'post'
WHEN maxtrx THEN 'pre'
ELSE 'pre'
END AS type
FROM mytable AS m
LEFT JOIN (
SELECT column1, column2, MIN(trx) AS mintrx, MAX(trx) AS maxtrx
FROM mytable
GROUP BY column1, colum... | How to compare 2 row in same table | [
"",
"mysql",
"sql",
""
] |
MySQL Table Diagram:

My query this far:
```
SELECT tblcourses.CourseStandard,
tblcourses.CourseID,
tblcourses.CourseRef,
tblcourses.CourseStandard,
tblcourses.CourseName,
... | This is pretty straightforward. Presumably you know the `StudentID` you'd like to see. Do a left join to the bookings table and select the mismatches.
```
SELECT tblcourses.CourseStandard,
tblcourses.CourseID,
tblcourses.CourseRef,
tblcourses.CourseStandard,
tblcour... | Do a left join to tblBookings on `courseID` where the `bookingID` is `null` (there are no matches). You'll have to provide the `studentID` as a parameter to the query.
```
SELECT DISTINCT c.CourseStandard,
c.CourseID,
c.CourseRef,
c.CourseStandard,
c.Cour... | I want to go down further into query, but not sure how | [
"",
"mysql",
"sql",
""
] |
I'm trying to read all the rows from a table on a SQL server and store them in string slices to use for later. The issue I'm running into is that the previously scanned rows are getting overwritten every time I scan a new row, even though I've converted all the mutable byte slices to immutable strings and saved the res... | You should create new slice for each data row. Notice, that a slice has a pointer to underlying array, so every slice you added into `results` have same pointer on actual data array. That's why you have faced with that behaviour. | When you create a slice using func make() it return a type (Not a pointer to type). But it does not allocate new memory each time a element is reassigned. Hence
result := make([]string, 5)
will have fix memory to contain 5 strings. when a element is reassigned, it occupies same memory as before hence overriding the o... | Go SQL scanned rows getting overwritten | [
"",
"sql",
"go",
""
] |
Hello I'm currently working on SQL problem that I can't quite figure out. Here is the Schema I'm working with:

Here is the question I am stuck on:
-- 3 Find the first name, last name and total combined film length of Sci-Fi films for every actor. T... | There is no need to use a subquery. Aggregate functions work on the entire data set. The 'group by' specifies how to group the data you're aggregating.
```
select a.actor_id, a.first_name, a.last_name, sum(f.length)
from actor a
left outer join film_actor fa on fa.actor_id = a.actor_id
left outer join film ... | This should get you exactly what you want, including the part about having actors that aren't in Sci-Fi movies. You can LEFT JOIN on film to include all films the film\_actor is in. The additional AND statement works with the LEFT JOIN to include actors not in Sci-Fi movies for your aggregate sum function.
```
SELECT ... | SQL query using sum() | [
"",
"mysql",
"sql",
""
] |
I have a table called "customers" which looks like this:
```
ID | NAME | ADDRESS | ZIP
John | Peterson | Street 2 | 45738
Jan | 74383 | Street 4 | 74383
Eric | Stone | 74383 | 74383
Julia| Carry | Street 9 | 74383
```
I want to replace any occurrence of "74383" with "". I have about 1.5 Million ro... | It is strange for me the requirement like this but, anyway, you can try this:
```
START TRANSACTION;
UPDATE customers
SET NAME = ''
WHERE NAME = '74383';
UPDATE customers
SET ADDRESS = ''
WHERE ADDRESS = '74383';
UPDATE customers
SET ZIP = ''
WHERE ZIP = '74383';
COMMIT;
``` | Assuming you mean in the `zip` column:
```
update customers
set zip = ''
where zip = '74383';
```
Note: you might prefer to set the value to `NULL` rather than the empty string (`''`), but your question explicitly suggests an empty string.
EDIT:
I would actually suggest that you use separate `update` statem... | Update whole table in SQL? | [
"",
"mysql",
"sql",
""
] |
I have a table `Ty` contains:
```
a integer NOT NULL,
b text,
c text,
d text,
e text
```
I'm trying to do insrert statment as follows:
```
insert into Ty (b,c,d,e) values
('hello','world',select current_date,select name from users where userid=4)
```
But it doesn't work. It says:
> ERROR:... | ```
insert into Ty (b,c,d,e)
SELECT 'hello','world',current_date, name from users where userid=4
``` | ```
insert into Ty (b,c,d,e)
select 'hello','world',current_date,name from users
where userid=4
``` | insert into table from query in Postgresql | [
"",
"sql",
"postgresql",
""
] |
I have one table, in which I want to update the value for a particular column. The column value should be row number. Based on a column distinct value I need to update the newly created column value.
Example:
Contents of `INFO_T` table:
```
Name | id
------------
Arijit | 120
Suman | 240
Priyam | 555
Arijit | 45... | You can use `dense_rank()` for this purpose:
```
select name, id, dense_rank() over (order by minid) as seqno
from (select t.*, min(id) over (partition by name) as minid
from table t
) t;
```
If you wanted to do this just with `row_number()`:
```
select t.name, t.id, tt.seqnum
from table t join
(sele... | [SQL FIDDLE DEMO](http://sqlfiddle.com/#!3/a1f07/9)
```
SELECT Table1.name, Table1.ID, SEQ.Seq_no
FROM
(SELECT name, ROW_NUMBER() OVER(order by name) as Seq_no
FROM (SELECT DISTINCT name FROM Table1) as unique_name ) as SEQ INNER JOIN
Table1 on SEQ.name = Table1.Name
``` | How to update a column value with ROW_NUMBER() OVER value based on distinct values of a column | [
"",
"sql",
"oracle",
"window-functions",
"row-number",
""
] |
I have to edit a stored procedure who has to return the sums of three columns having nullable values. If there is a `null` value, I need to cast it to `0`
Here is a screenshot of data :

And here is the originial request using the first column only ... | ```
--ANSI standard
SELECT SUM(COALESCE(col1,0)) + SUM(COALESCE(col2,0)) + SUM(COALESCE(col3,0))
--SQL Server Style
SELECT SUM(ISNULL(col1,0)) + SUM(ISNULL(col2,0)) + SUM(ISNULL(col3,0))
--The one wthout functions. It will work the same as previous OR FASTER.
SELECT SUM(CASE WHEN col1 IS NULL THEN... | In Sql Server, (and probably in most if not all relational databases) the [`SUM`](https://msdn.microsoft.com/en-us/library/ms187810.aspx?f=255&MSPPError=-2147217396) Aggregation function [ignores null values](http://sqlfiddle.com/#!3/3171d/1) by default, so there really is no need to use [`coalesce`](https://msdn.micro... | Sum on multiple columns with nullable values | [
"",
"sql",
"sql-server",
""
] |
I have a table which logs the HTTP status code of a website whenever the status changes, so the table looks like this...
```
id status date
-----------------------------------
1 404 2015-10-01 13:30:00
2 200 2015-10-02 13:30:00
3 404 2015-10-03 13:30:00
```
I want to... | Here is [SQL FIDDLE DEMO](http://sqlfiddle.com/#!9/b2242/1)
```
SELECT t1.status
,COUNT(t1.id) as status_count
,SUM(IF(t2.date IS NULL, NOW(), t2.date)-t1.date) / (NOW()-t3.start_date) as duration
FROM table_name t1
LEFT JOIN table_name t2 ON t1.id = (t2.id - 1)
,(SELECT MIN(date) as start_d... | Mine is more complicated than nick but give a different result.
And i try it on excel to verify values are correct.
I start date with `2015-07-01 13:30:00` so `NOW()` function can work
That mean seconds are
```
404 | 86400 1 day | 0.05101
200 | 86400 1 day | 0.05101
404 | 1521138 17 days | 0.89799
... | Calculating duration percentage | [
"",
"mysql",
"sql",
""
] |
Simple question but I am confused about the query, I have three tables
First table: projects
```
proj_id project_cost project_description
------- ------------ -------------------
1 123.45 construction plan A
2 222.22 construction plan B
3 333.3... | Right, I couldn't test this atm but I would do something like this:
```
SELECT
proj_id,
project_estimates.Q1,
project_estimates.Q2,
project_estimates.Q3,
project_estimates.Q4,
project_expenditure.Q1,
project_expenditure.Q2,
project_expenditure.Q3,
project_expenditure.Q4
FROM project... | The answer should be first an INNER join as you want only projects with estimates in 2015-16 and then a LEFT join as you want it to get populated by NULL if the entry is not there :
```
SELECT prj.proj_id,
prj_est.Q1,
prj_est.Q2,
prj_est.Q3,
prj_est.Q4,
prj_exp.Q1,
prj_exp.Q2,... | joining multiple tables | [
"",
"sql",
"oracle",
""
] |
I am inserting records using left joining in Hive.When I set limit 1 query works but for all records query get stuck at 99% reduce job.
Below query works
```
Insert overwrite table tablename select a.id , b.name from a left join b on a.id = b.id limit 1;
```
But this does not
```
Insert overwrite table table... | If your query is getting stuck at 99% check out following options -
* Data skewness, if you have skewed data it might possible 1 reducer is doing all the work
* Duplicates keys on both side - If you have many duplicate join keys on both side your output might explode and query might get stuck
* One of your table is sm... | Here are a few Hive optimizations that might help the query optimizer and reduce overhead of data sent across the wire.
```
set hive.exec.parallel=true;
set mapred.compress.map.output=true;
set mapred.output.compress=true;
set hive.exec.compress.output=true;
set hive.exec.parallel=true;
set hive.cbo.enable=true;
set h... | Hive query stuck at 99% | [
"",
"sql",
"hadoop",
"hive",
"mapreduce",
"hiveql",
""
] |
I'm using *SQL-Server 2008*. I need to combine rows with the same `Name` and increase counter when:
1. 1 or more `Id's` for the same `Name` is `blank`
2. NOT merge rows if `Id` is `NULL`!
3. NOT merge rows if have the same `Name`, but different `Ids`
**Output for now:**
```
Name Id Cnt
John 1 1
Peter 2... | **Edit**
```
DECLARE @Data table (Name varchar(10), Id varchar(10)) -- Id must be varchar for blank value
INSERT @Data VALUES
('John', '1'),
('Peter', '2'),('Peter', '2'),
('Peter', '3'),--('Peter', ''), --For test
('Lisa', '4'),
('Lisa', NULL),
('David', '5'),
('David', ''),
('Ralph', ''), ('Ralph', '')
```
---
``... | You can use `CASE` statement inside your `SELECT`. It allows you to set Id = [some value] for employees where it is blank. Query can be something like this:
```
SELECT E.Name,
CASE
WHEN E.Id = ''
THEN
(Select Employees.Id from Employees whe... | Combine rows if value is blank | [
"",
"sql",
"sql-server",
"t-sql",
"merge",
"group-by",
""
] |
For serveral times I've been returning to understanding of database relational theory, and still I don't have success. I'll try once more.
Let's say I have two tables:
animals:
```
CREATE TABLE animals (id INTEGER PRIMARY KEY, name TEXT);
```
and food:
```
CREATE TABLE food (id INTEGER PRIMARY KEY, food TEXT);
```
... | That's how you implement such a many-to-many relationship:
* [How to implement a many-to-many relationship in PostgreSQL?](https://stackoverflow.com/questions/9789736/how-to-implement-a-many-to-many-relationship-in-postgresql/9790225#9790225)
And you can accomplish the task you describe with a ***single*** query usin... | You need a junction table, that related `Animals` and `Food`. This would look like:
```
CREATE TABLE AnimalFoods (
id INTEGER PRIMARY KEY,
AnimalId int references Animal(id),
FoodId int references Food(id)
);
```
You can then answer your questions using various joins among these tables. | SQL and relations between tables | [
"",
"sql",
"postgresql",
""
] |
I have a table like:
```
create table tbl (
id int,
data image
)
```
It's found that the column `data` have very small size, which can be stored in `varbinary(200)`
So the new table would be,
```
create table tbl (
id int,
data varbinary(200)
)
```
How can I migrate this table to new design ***withou... | Just do two separate [`ALTER TABLE`](https://msdn.microsoft.com/en-GB/library/ms190273.aspx)s, since you can only convert `image` to `varbinary(max)`, but you can, afterwards, change its length:
```
create table tbl (
id int,
data image
)
go
insert into tbl(id,data) values
(1,0x0101010101),
(2,0x0204081632)
go
al... | You can use this ALTER statement to convert existing column `IMAGE` to `VARBINARY(MAX)`. [Refer Here](http://www.sqlservercentral.com/Forums/Topic914594-149-1.aspx)
```
ALTER Table tbl ALTER COLUMN DATA VARBINARY(MAX)
```
After this conversion, you are surely, get your data backout.
NOTE:- Don't forgot to take backu... | Convert table column data type from image to varbinary | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2014",
"alter-table",
""
] |
If given the Average for 24 hours for each date in a year. I want to spread this hourly average to average at each minute.
e.g. given
```
Date Time Average
01-Jan-15 23:00 20
02-Jan-15 00:00 50
02-Jan-15 01:00 30
```
I want the output to be calculated something as below ....
```
DateTime ... | EDIT: Added union to include the final missing row
Some thing like this may work. Assuming the input data is in table a,
```
with b as
(select level-1 lev
from dual
connect by level <= 60
),
v as
(
select start_date, value current_value, lead(value) over (order by start_date) next_value
from a
)
select start_date+ (l... | You can use [recursive subquery factoring](http://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_10002.htm#BCEJGIBG) to do the interval halving, and find the weighted average (or whatever this calculation is supposed to be finding) for each step:
```
with r (period_start, period_average, step, step_start, s... | How to spread the average between two intervals in oracle | [
"",
"sql",
"oracle",
"oracle11g",
"intervals",
""
] |
I have a table like this:
```
T A B C ID
2015-07-19 a b c 1
2015-07-16 a y z 2
2015-07-21 a b c 1
2015-07-17 a y c 2
2015-07-18 a y c 1
2015-07-20 a b c 1
2015-07-17 a y c 1
2015-07-19 a b c 2
2015-07-1... | This query gives the expected result (tested):
```
SELECT t1.* FROM mytable t1
LEFT JOIN mytable t2 ON t1.t = t2.t + INTERVAL 1 DAY AND t1.A = t2.A AND t1.B = t2.B AND t1.C = t2.C AND t1.ID = t2.ID
WHERE t2.T IS NULL
ORDER BY t1.ID, t1.T DESC
``` | Try this query:
```
SELECT max(t),a,b,c,id FROM table GROUP BY A,B,C,id ORDER BY ID, max(T)
``` | MySQL - Select distinct detecting changes on different ordered rows | [
"",
"mysql",
"sql",
"distinct",
""
] |
I have this query:
```
select top 5 * from tbl_post ORDER BY Id DESC
```
I want to select the first 5 rows after the 20th row. How I can do this? | Use OFFSET and FETCH [MSDN OFFSET FETCH Clause](https://technet.microsoft.com/en-us/library/gg699618%28v=sql.110%29.aspx):
```
SELECT * FROM tbl_post ORDER BY whatever OFFSET 20 ROWS FETCH NEXT 5 ROWS ONLY;
```
Note that you have to order by something for this to work, and you cannot use `top` at the same time | ```
with x as (select row_number() over(order by id desc) as rn, * from tbl_post)
select t.*
from x join tbl_post t on x.id = t.id
where x.rn between 20 and 25
```
This is the easiest way to assign row numbers and selecting the rows you need later on. | How to select top 5 after 20 rows | [
"",
"sql",
"sql-server",
""
] |
I have two separate queries that work fine by themselves but I need them to work in one query. I can combine the results easily enough in excel but this is to be part of a larger query.
The two separate queries are:
```
SELECT
SiteProductVariation.ProductVariationID,
COUNT(SiteProduct.SiteProductID) AS Expr... | ```
SELECT SiteProductVariation.ProductVariationID
, COUNT(CASE WHEN SiteProduct.ProductDisplay = 0 THEN SiteProduct.SiteProductID END) AS Expr1
, COUNT(CASE WHEN SiteProduct.ProductDisplay = 1 THEN SiteProduct.SiteProductID END) AS Expr2
FROM SiteProductVariation
INNER JOIN SiteProduct ON Site... | You can do it like this:
```
SELECT SiteProductVariation.ProductVariationID,
SUM(CASE WHEN SiteProduct.ProductDisplay = 0 THEN 1 ELSE 0 END) AS Expr1,
SUM(CASE WHEN SiteProduct.ProductDisplay = 1 THEN 1 ELSE 0 END) AS Expr2
FROM SiteProductVariation INNER JOIN
SiteProduct ON SiteProd... | Two counts in one query with opposing where criteria | [
"",
"sql",
"sql-server",
"count",
"group-by",
""
] |
This is a bit specific so please bear with me...
I want my where statement to give me all the results that meet the following criteria:
```
WHERE
TestCode = A1
AND
TestResult > 50
AND
TestCode = A2
AND
TestResult > 200
```
In real terms I want a list of all the patients that have both an `A1>50` whilst also having ... | Were you looking to do something like this?
```
WHERE ((TestCode = A1) AND (TestResult > 50)) OR ((TestCode = A2) AND (TestResult > 200))
```
It looks like your testing for `WHEN TestCode = 'A1'` `AND` `WHEN TestCode = 'A2'` Which would be impossible for them to equal both at the same time, returning empty. | I think the syntax you're after is:
```
SELECT *
FROM your_table AS A
WHERE EXISTS (
SELECT TOP 1 1
FROM your_table AS A1_50
WHERE A1_50.ID = A.ID
AND A1_50.TestCode = 'A1'
AND A1_50.TestResult > 50)
AND EXISTS (
SELECT TOP... | SQL Where condition a is met and condition b is met No Results | [
"",
"sql",
""
] |
How can we get last day of the month through month name in Postgresql? | Try this way :
```
select date_trunc('month', to_date('January ', 'Month'))+'1month'::interval-'1day'::interval
```
To parse a date object from a month name you can try this way :
```
to_date('January', 'Month')
``` | ```
SELECT
DATE_PART('days', DATE_TRUNC('month', NOW())
+ '1 MONTH'::INTERVAL - DATE_TRUNC('month', NOW())
)
```
You can use any date instead now | Last Date of the Month in Postgres Sql | [
"",
"sql",
"postgresql",
""
] |
I have a table that has four columns: `id`, `item_number`, `feature`, `value`.
The table looks like this and has about 5 million entries.
```
╔════╦═════════════╦═════════╦═══════╗
║ id ║ item_number ║ feature ║ value ║
╠════╬═════════════╬═════════╬═══════╣
║ 1 ║ 234 ║ 5 ║ 15 ║
║ 2 ║ 234 ║... | In your query, add
`order by item_number desc`
If you are trying to query based on a specific feature, so only receive one set of data for a feature at at time, add
`where feature = 'feature'`
where "feature" is the feature value you want to search for. If you are looking to provide all features but sort them, you ... | Using `order by` with `desc` and `where` clauses:
```
select `item_numbers`
from `tbl`
where `feature` = 5
order by `value` desc
``` | MySQL data sort | [
"",
"mysql",
"sql",
"sorting",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.