Last updated May 25, 2010. Created by Crell on September 18, 2008.
Edited by duellj. Log in to edit this page.
Delete queries must always use a query builder object. They are started using the db_delete() function as follows:
<?php
$query = db_delete('node', $options);
?>That creates a delete query object that will delete records to 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, that 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.
<?php
$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.
Comments
Delete on join?
I don't see anything in the documentation for how to delete a row based on a join, ie, the following SQL syntax (MySQL)
DELETE term_node FROM term_node tn JOIN node n on tn.vid=n.vidWHERE tn.tid = 1234 and n.nid=9999;
ie, without knowing the node's vid, using the above SQL query, I can still delete the correct row from the term_node table.
If I use db_delete() syntax, however, it appears I'm going to have to do a select to find the current vid for the node, and then do a single-table delete query against term_node, which is a huge waste.