2

This is the same query I used in the past for a DATE field, however for a DATETIME field it doesn't work.

SELECT
    *
FROM 
    user_log
WHERE 
    log_updated = DATE_SUB(DATE(NOW()), INTERVAL 21 DAY);

I want a date from EXACTLY 21 days ago, but it can be of any time during that day. I do not want 21 days and over (or 21 days and under).

S3S
  • 24,809
  • 5
  • 26
  • 45
Hana
  • 85
  • 1
  • 9

2 Answers2

4

You can do the following:

SELECT
    *
FROM 
    user_log
WHERE 
    DATE(log_updated) = DATE(NOW() - INTERVAL 21 DAY);

But then this is not an efficient (sargable) solution, as using a function on the Column will impede the usage of indexing (if defined).

So, a better approach would be:

SELECT
    *
FROM 
    user_log
WHERE 
    log_updated >= DATE(NOW() - INTERVAL 21 DAY) AND 
    log_updated < DATE(NOW() - INTERVAL 20 DAY)

Notice that I have used a day after the required date for maximum bound checking (not inclusive). It is obtained by INTERVAL -20 DAY

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
0

Since DATE(NOW()) is the same as CURDATE(), you may as well use

WHERE log_updated >= CURDATE() - INTERVAL 21 DAY
  AND log_updated  < CURDATE() - INTERVAL 20 DAY

This may use an index on log_updated.

In contrast, DATE(log_updated) ... cannot use an index on log_updated.

Rick James
  • 135,179
  • 13
  • 127
  • 222