Skip to content

Database API - Give greater clarity as to when to use db_query vs db_select and friends #256

@yorkshire-pudding

Description

@yorkshire-pudding

In the function doc for db_query it says:

Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db_select() instead.

In the Database API documentation (copied from D7) we have on the Static Queries page:

The most common SELECT queries in Backdrop are static queries using the db_query() function. Static queries are passed to the database nearly verbatim, as in the following example.

$query = db_query("SELECT nid, title FROM {node}");
$records = $query->fetchAll();
foreach ($records as $record) {
// Do something.
}

Only very simple SELECT queries should use the static query mechanism. You should use a dynamic query if you need more complex queries, dynamic query generation or alterability.

It is not clear what is a very simple static query and these issues from the Drupal issue queue suggest there are performance penalties to using db_select unless you absolutely have to:

Areas I think it would be useful to cover:

  • Is a query with placeholders that refer to variables ok for db_query?
  • What about JOIN clauses?
  • Examples of what some of the edge cases of each might be and why you would go to either db_query or db_select

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions