4.6.x core.php hook_db_rewrite_sql($query, $primary_table, $primary_field, $args)
4.7.x core.php hook_db_rewrite_sql($query, $primary_table, $primary_field, $args)
5.x core.php hook_db_rewrite_sql($query, $primary_table, $primary_field, $args)
6.x core.php hook_db_rewrite_sql($query, $primary_table, $primary_field, $args)

Rewrite database queries, usually for access control.

Add JOIN and WHERE statements to queries and decide whether the primary_field shall be made DISTINCT. For node objects, primary field is always called nid. For taxonomy terms, it is tid and for vocabularies it is vid. For comments, it is cid. Primary table is the table where the primary object (node, file, term_node etc.) is.

You shall return an associative array. Possible keys are 'join', 'where' and 'distinct'. The value of 'distinct' shall be 1 if you want that the primary_field made DISTINCT.


$query: Query to be rewritten.

$primary_table: Name or alias of the table which has the primary key field for this query. Typical table names would be: {blocks}, {comments}, {forum}, {node}, {menu}, {term_data} or {vocabulary}. However, it is more common for $primary_table to contain the usual table alias: b, c, f, n, m, t or v.

$primary_field: Name of the primary field.

$args: Array of additional arguments.

Return value

An array of join statements, where statements, distinct decision.

Related topics

1 function implements hook_db_rewrite_sql()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

node_db_rewrite_sql in modules/node/node.module
Implementation of hook_db_rewrite_sql


developer/hooks/core.php, line 436
These are the hooks that are invoked by the Drupal core.


function hook_db_rewrite_sql($query, $primary_table, $primary_field, $args) {
  switch ($primary_field) {
    case 'nid':

      // this query deals with node objects
      $return = array();
      if ($primary_table != 'n') {
        $return['join'] = "LEFT JOIN {node} n ON {$primary_table}.nid = n.nid";
      $return['where'] = 'created >' . mktime(0, 0, 0, 1, 1, 2005);
      return $return;
    case 'tid':

      // this query deals with taxonomy objects
    case 'vid':

      // this query deals with vocabulary objects


jamesHF’s picture

This will be replaced with hook_query_alter() in Drupal 7.