Drupal7 Database API: Insert, Update, Delete and Merge queries

Before examining the specific db_insert, db_update, db_merge options, it is worth noting that
drupal_write_record($table, &$record, $primary_keys = array()) 'Saves (inserts or updates) a record to the database.', and may handle a lot of cases easily, but:
Do not use drupal_write_record() within hook_update_N() functions, since the database schema cannot be relied upon when a user is running a series of updates. Instead, use db_insert() or db_update() to save the record.

From Dynamic queries:

Dynamic queries refer to queries that are built dynamically by Drupal rather than provided as an explicit query string. All Insert, Update, Delete, and Merge queries must be dynamic. Select queries may be either static or dynamic. Therefore, "dynamic query" generally refers to a dynamic Select query.

Note: in 90% of select query use cases you will have a static query. If in a critical performance path, you should use db_query() and friends instead of db_select() for performance reasons. Only use dynamic queries if the query parts vary (example: adding WHERE conditions depending on the context) or if they should be alterable (example: node access). Note: Varied opinions exist on this ...


Once the query is built, call the execute() method to compile and run the query.

$result = $query->execute();

The execute() method will return a result set / statement object that is identical to that returned by db_query(), and it may be iterated or fetched in the exact same way:

$result = $query->execute();
foreach ($result as $record) {
  // Do something with each $record
Visit also