How can I query a condition that deletes the rows with column Date older than the last 30 days in DBTNG format?

I have tried this, but it's wrong.

$connection = \Drupal::database();
    ->condition('Date', now() . ' - INTERVAL 30 day', '>');

Screenshot of table with nid and Date columns

  • Is it a created date? you try using EntityTypeManager to query the condition, then loop and delete them one by one. I would do it using a batch approach. Jul 27, 2023 at 9:00
  • 4
    PHP’s now() function (a deprecated alias for time()), which that code calls, returns the current Unix timestamp. You can’t subtract “INTERVAL 30 day” from it.
    – cilefen
    Jul 27, 2023 at 9:49

1 Answer 1


Considering that the field Date is type date and has values with the following format: Y-m-d (2023-04-04).

// Returns a timestamp equivalent to: 2023-07-01 17:20:53 UTC (today is 2023-07-31)
$range = strtotime('now -30 days'); 

// Converts the previous timestamp to Y-m-d format
$rangeTimestamp = date('Y-m-d', $range); 

// Stores the database service into a variable
$connection = \Drupal::database();
// Query that retrieves rows with column Date (Y-m-d) with a value older than specific range. 
$query =  $connection->delete('my_table')
          ->condition('Date', $rangeTimestamp, '<=')

// If Date is greater or equal '>=', it's inside the range of 30 days.
// If Date is lower or equal '<=', it's outside the range, and is older than 30 days.
  • Actually, $range contains a timestamp and $rangeTimestamp contains a date string. The first variable should be really named $rangeTimestamp, and the second variable should be named $range. Actually, they are not ranges, so their names should not contain range.
    – apaderno
    Aug 1, 2023 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.