Delete queries

Last updated on
14 October 2016

Delete queries must always use a query builder object. They are started using the db_delete() function as follows:

$query = db_delete('node', $options);

That creates a delete query object that will delete records from the node table. Note that braces are not required around the table name as the query builder will handle that automatically.

The delete query object uses a fluent API. That is, all methods (except execute()) return the query object itself allowing method calls to be chained. In many cases, this means the query object will not need to be saved to a variable at all.

Delete queries are conceptually very simple, consisting of only a WHERE clause. The full structure of the WHERE clause is detailed in the section on Conditional clauses, and will only be touched on here.

A full Delete query will take the following form:

$num_deleted = db_delete('node')
  ->condition('nid', 5)
  ->execute();

The above query will delete all rows from the {node} table where the nid column is 5. It is equivalent to the following query:

DELETE FROM {node} WHERE nid=5;

The execute() method will return the number of records that were deleted as a result of the query.