Search code examples
sqldatecrondatediff

How to be sure to not lose values when select the ID of last X days in SQL


To give you a context of my problem: I want to receive by email the ID and date of creation of the stuff created during the 15 last days.

I want to call a function each 15 days in PHP. I do that by creating a CRON task which be triggered each of 1st and 16th of the month. This is my request SQL request :

SELECT ID,
       creation_date
FROM mytable
WHERE creation_date > DATE_SUB (NOW (), INTERVAL 16 DAY)

I'm worried about losing values. What is the good method to do that? Thanks.


Solution

  • The simplest solution :

    Add a column isNotified in your table like this :

    | ID | creation_date | isNotified |
    |----|---------------|------------|
    | 1  | 2020-03-26    | 1          |
    | 2  | 2020-04-09    | 0          |
    | 3  | 2020-04-10    | 0          |
    

    Then, update your request to select only the non already sent items :

    SELECT ID,creation_date FROM mytable WHERE isNotified=false
    // Send your mail
    

    If send is OK, update the column to set isNotified as True like that :

    UPDATE mytable SET isNotified = true WHERE isNotified = false
    

    Set the CRON tab to trigger 1st and 15th of month.