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:

if ($day == 'today') {
    $date = date('Y-m-d H:i:s');
} elseif ($day == 'yesterday') {
    $date = date('Y-m-d H:i:s', strtotime('yesterday'));
} else {
    ...
}

$sql = "SELECT * FROM all_forms_main_contact WHERE DATEDIFF(timestamp, '" . $date . "') <= 1";
$mc = DB::select($sql);
return json_encode($mc);

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:

SELECT * FROM `tbl` WHERE `datetime` >= NOW() - INTERVAL 1 DAY

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

SELECT * FROM `tbl` WHERE `datetime` >= NOW() - INTERVAL 2 DAY

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

SELECT * FROM `tbl` WHERE `datetime` >= CURDATE()

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:

SELECT * FROM `tbl` WHERE `datetime` >= CURDATE() - INTERVAL 1 DAY AND `datetime` < CURDATE()

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