Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in SQL by (20.3k points)

I have a query like this:

SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01' AND '2013-05-01'

But this gives no results even though there is data on the 1st.

created_at looks like 2013-05-01 22:25:19, I suspect it has to do with the time? How could this be resolved?

It works just fine if I do larger date ranges, but it should (inclusive) work with a single date too.

1 Answer

0 votes
by (40.7k points)

For larger date ranges also, it is (inclusive) i.e. work with a single date too. You are trying to compare datetimes to dates. But, the second date is interpreted as midnight when the day starts.

Use the below code to fix it:

SELECT *

FROM Cases

WHERE cast(created_at as date) BETWEEN '2013-05-01' AND '2013-05-01'

Otherwise, you can do explicit binary comparisons like this:

SELECT *

FROM Cases

WHERE created_at >= '2013-05-01' AND created_at < '2013-05-02'

Aaron Bertrand has a long blog entry on dates (here), where he discusses this and other date issues.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 23, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...