Skip to content
Advertisement

Having trouble with WHERE DATEDIFF in my SQL

I think I’m going about this wrong. I want to pull the rows in my database that are less than a day old, in PHP. I’m using Laravel, but that’s not relevant. Here is what I have:

However, that isn’t return the right results. It’s return results older than a day.

Advertisement

Answer

This query selects rows that are newer than -24 hours.
For example if it is 04:00 AM then return all rows >= yesterday 04:00 AM:

Likewise for newer than -48 hours.
For example if it is 04:00 AM then return all rows >= day before yesterday 04:00 AM:

This query selects today’s rows.
For example if it is 04:00 AM then return all rows >= today 00:00 AM:

Likewise, this query selects yesterday’s rows only.
For example if it is 04:00 AM then return all rows between yesterday 00:00 AM through (but not including) today 00:00 AM:

I use the above syntax for dates queries, which I believe is far more readable than date add/sub functions.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement