Why is my SQL query returning extra rows?

0
8
Asked By CodingNinja77 On

I'm learning SQL for my job and trying to filter orders by date. I ran a query to retrieve orders created in January 2024, but it returns more rows than I anticipated. Here's what I've done so far: I've adjusted the `WHERE` condition, searched for information using the phrase "sql between date inclusive," and removed joins step by step. My simplified query looks like this:

SELECT *
FROM orders
WHERE created_at >= '2024-01-01'
AND created_at <= '2024-01-31';

I expected to see only the data from January, but I'm still encountering some rows from February. Could this be related to how timestamps work that I'm not grasping?

2 Answers

Answered By QueryWizard01 On

It sounds like a timestamp issue. Your `created_at` column likely stores full datetime values, like `2024-01-31 23:59:59`. When you compare it with `<= '2024-01-31'`, it only checks up to midnight of that day. Try changing your condition to `AND created_at < '2024-02-01'` to include everything right up until the last second of January.

CuriousLearner5 -

But wouldn't that exclude any rows from January 31st after noon?

Answered By DataDude92 On

Check the time part of your timestamp. If you’re using `<= '2024-01-31'`, it might include February rows since it's looking at the entire day, not just the date.

CuriousLearner5 -

That shouldn't be the case, right?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.