Craft CMS database queries

Published

Reviewedbyfl

Craft CMS writes the SQL for every element query in a template. Find the slow and repeated queries before a growing dataset makes them visible in production.

About Craft CMS database queries

Craft CMS models all content as elements: entries, assets, users, categories. Templates query them through Twig without SQL, and Craft builds the joins behind the scenes. That convenience hides how many queries a page runs and how expensive each one is. Sites with large amounts of entries and fields and frequent content updates suffer most.

Slow queries are easy to miss during development, where the local dataset is small. In production, once all pages are published, query runtime grows with the data. The general database performance tips cover slow queries and indexes for any PHP app.

Common anti-patterns

  • Queries in nested loops (N+1)
  • where conditions on custom fields
  • orderBy on custom fields

The fix for N+1 queries is eager-loading: Craft loads the related elements for all entries in one query. See the official Craft documentation on eager-loading, including lazy eager-loading with .eagerly().

Craft 5 stores custom field values in one JSON column, without an index per field. See what columns are indexed in Craft and how database indexing works.

Use the Craft debug toolbar

Craft CMS integrates the Yii debug toolbar, which shows query counts and execution times per page. Enable it in the user preferences of the Control Panel. A page that runs more than 50 queries is worth a closer look.

Use the Relax plugin

The Relax plugin reduces write load on the database: it limits queue messages, skips useless terms in the search index and writes deprecation notices in dev environments only. fortrabbit co-founder Oliver Stark released it for free.

Written by humans and AI in collaboration.

AI use & editorial processEdit on GitHub ↗