Drupal's vendor-agnostic database abstraction layer provides a unified database query API that can query different underlying databases. It is built upon the PHP Data Objects (PDO) database API and inherits much of its syntax and semantics.

The Database API is designed to preserve the syntax and power of SQL as much as possible. It also:

  • Supports multiple database servers
  • Allows developers to leverage more complex functionality (i.e., transactions)
  • Provides a structured interface to dynamically construct queries
  • Enforces security checks
  • Provides modules with an interface for modifying other queries in the system

The Database API may not always be the best option for interacting with data. API use in Drupal is usually situational, e.g. using the Node API for Node CRUD operations, or the more generic Entity API for Entity for CRUD, the Configuration API for accessing configuration data, etc. We generally recommend directly querying the database as a last resort.

Example tasks

  • Create a new database table for storing custom data
  • Insert and retrieve data from a custom table or set of tables
  • Query the watchdog table for log messages


Drupal's database abstraction layer did not change significantly between Drupal 7 and Drupal 8+ and has been quite stable for some time. The primary difference in the current version of Drupal is that access to the database should be done via a database connection service instead of the now deprecated db_* functions. Query syntax and use of result sets remain similar.

Drupalize.Me resources

In Drupal the preferred method in most cases for storing and retrieving data is via the Entity API.


Note: Use the service container to get a query object. After which queries work almost identically to Drupal 7.

$connection = \Drupal::database();
$query = $connection->select('node', 'n');

More Guides

We have guides on many Drupal skills and topics.

Explore guides

External resources

  • Database API (Drupal.org)
    • Detailed documentation on how to query a database using Drupal's API.
  • Database abstraction layer (api.drupal.org)
    • Technical documentation for the database abstraction layer. Use this if you just need a quick reminder about how a particular feature works.