2

I am having trouble with the following simple query

SELECT * FROM users WHERE Created = '28/02/2013'

The issue is the column CREATED is a datetime datatype, so the query executes fine as long as the timestamp is 0:00:0, if the time stamp is set to say 12:00, then the query does not return a result set.

Any idea why?

Thanks

1
  • 1
    xkcd.com/1179 Commented Feb 28, 2013 at 14:21

4 Answers 4

3

Because you are not specifying the time, so it assumes that you are doing:

SELECT * FROM users WHERE Created = '28/02/2013 00:00:00'

If you want the whole day, then you need a range of times:

SELECT * 
FROM users 
WHERE Created >= '20130228' AND Created < '20130301'

Also, please use non ambiguous format for dates ('YYYYMMDD') instead of other formats.

Sign up to request clarification or add additional context in comments.

2 Comments

@DavidB No, I do mean 'YYYYMMDD' for SQL Server since its not ambiguous on that RDBMS (for DATETIME and DATE datatypes). (Though 'YYYY-MM-DD' is also not ambiguous for DATE datatype).
@DavidB: SQL Server's interpretation of "ISO-8601" for DATETIME truly is only YYYYMMDD (no dashes!). With the dashes - which would be the "normal" ISO-8601 standard does not work for all language settings - it can (and will) fail for e.g. "German" or "UK British" (or pretty much any European langauge) language settings...
1
SELECT * FROM users WHERE CAST(Created AS DATE) = '28/02/2013'

will fix it, but be careful, it disables indexes

SELECT * FROM users WHERE Created BETWEEN '28/02/2013 00:00' AND '28/02/2013 23:59'

And this will use index

2 Comments

You shouldn't use BETWEEN if the time part is important. What happens with values like '20130228 23:59:59', they will get filtered out
It's just an example, for sure you can specify seconds if needed too
1

If you don't need to consider time: try to convert created field to date and then compare as;

SELECT * FROM users WHERE convert(date,Created) = '28/02/2013'

--this would be even better with iso date format (not culture specific)
SELECT * FROM users WHERE convert(date,Created) = '20130228' --yyyymmdd format

Comments

-1

You have to convert the column into date and then compare

SELECT * FROM users WHERE CONVERT(VARCHAR(11), Created, 106) = '28 Feb 2013'

2 Comments

SELECT * FROM users WHERE convert(varchar(20),a.time_inserted,101)='02/28/2013'
The risk with this solution is that you're doing a string compare instead of date compare. So, you must be careful to match date formats.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.