Last updated January 2, 2018

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 8 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 Drupal 8 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

We are still filling out our Drupal 8 library and this page will be updated with new tutorials as they are created.

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


Note: For Drupal 8 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 (
    • Detailed documentation on how to query a database using Drupal's API.
  • Database abstraction layer (
    • Technical documentation for the database abstraction layer. Use this if you just need a quick reminder about how a particular feature works.
  • Drupal 8 API: database abstraction layer (
    • Follow worked-out examples of how to utilize Drupal's database abstraction layer to perform CRUD operations on a Drupal 8 site.