# Optimize database queries

- Check 06.15 · Performance and Core Web Vitals · Important
- Source: https://checklist-seo-geo.com/en/performance-core-web-vitals/optimize-database-queries
- Find slow or excessive SQL queries and fix them: EXPLAIN, indexes, N+1, object caching, on MySQL, PostgreSQL, WordPress, Laravel and Symfony.
- Updated on 2026-11-25
- Licence: CC BY 4.0. Credit “Checklist SEO & GEO” with a link to https://checklist-seo-geo.com/en/performance-core-web-vitals/optimize-database-queries.
- Plugin checklist-seo-geo: 1.3.1 · https://github.com/maximegaul/checklist-seo-geo

## In short

Before sending the first byte of a page, the server queries the database. A few slow queries, or hundreds of small repeated ones, are enough to push the response time up. This check consists of measuring what each template actually does, fixing the costly queries (indexes, rewriting, batch loading) and caching whatever can be cached. Expected result: a short, stable generation time, including on pages that do not go through the page cache.

## Why it matters

TTFB (Time To First Byte, the delay before the first byte of the response) caps everything else: the browser cannot display anything until the HTML starts arriving. On a dynamic site, the database is the largest component of this delay.

A page cache hides the problem without solving it. It does not serve personalized pages (cart, account, internal search), the first visit after a purge, or the deep URLs that only crawlers request. Yet these are precisely the URLs Googlebot crawls in large numbers: Google states that it adapts its crawl rate to the speed and stability of the server's responses. A site that responds slowly is crawled more slowly.

Three causes come up almost every time:

- **A missing index**: the database reads the whole table to find a few rows.
- **The N+1 problem**: one query loads a list of N items, then the code runs one extra query per item (the author of each article, the image of each product).
- **Work redone on every page**: a computation that is identical for all visitors (menu, best sellers, counters) runs again on every HTTP request for lack of caching.

## What it improves

- **TTFB**, and therefore **LCP** (Largest Contentful Paint, the display of the largest visible element): every millisecond saved on the server side is saved for every loading metric. See [target TTFB ≤ 800 ms as a benchmark](https://checklist-seo-geo.com/en/performance-core-web-vitals/target-ttfb-800-ms-as-benchmark).
- **Crawling**: fast responses without 5xx errors let crawlers crawl more URLs. The effect is mostly noticeable on large sites.
- **Load handling**: a traffic spike or a crawler visit no longer saturates the database.
- **Costs**: less CPU and memory used, and a server upgrade pushed back.
- **Rankings**: indirect effect, through Core Web Vitals.

## How to check

Measure the TTFB of a page served without a cache (internal search results, cart, or any URL excluded from the cache):

```bash
curl -s -o /dev/null -w "TTFB: %{time_starttransfer} s\n" "https://example.com/recherche?q=test"
```

Repeat the measurement several times. Compare it with a static file on the same server: if the static file responds quickly and the dynamic page slowly, the time is being lost in the application or the database.

Then count the SQL queries per page with your platform's tool (detailed below):

| Platform | Diagnostic tool |
| --- | --- |
| WordPress | Query Monitor |
| Laravel | Laravel Debugbar, Telescope, Pulse |
| Symfony | Web Profiler, Doctrine panel |
| Drupal | Webprofiler module |
| PrestaShop | profiling mode |
| Magento | query log, profiler |
| Any database | slow query log |

Compliant result: no duplicate queries in series, no query above your slowness threshold on the main templates, and a number of queries that does not depend on the number of items displayed.

## How to implement

### Before you start

Always proceed in this order: measure, identify the query, read its execution plan, fix it, measure again. An index added at random slows down writes without speeding anything up.

Work on a recent copy of the production database: a query that is instant on an almost empty table can become very slow at real volume.

### MySQL and MariaDB

Enable the slow query log in the configuration file (`/etc/mysql/mysql.conf.d/mysqld.cnf`, or `/etc/mysql/mariadb.conf.d/50-server.cnf` for MariaDB):

```ini
[mysqld]
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 1
```

Restart the service, or enable it on the fly, without a restart:

```sql
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
```

After a few hours of real traffic, summarize the log:

```bash
sudo mysqldumpslow -s t -t 10 /var/log/mysql/mysql-slow.log
```

The `pt-query-digest` tool (Percona Toolkit) gives a more detailed ranking. Take the first query in the ranking and ask for its execution plan:

```sql
EXPLAIN SELECT id, total FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10;
```

| Column | Warning sign |
| --- | --- |
| `type` | `ALL`: the whole table is read |
| `key` | `NULL`: no index used |
| `rows` | far higher than the number of rows returned |
| `Extra` | `Using filesort`, `Using temporary` on a large table |

Create the index that matches the query: the columns compared for equality first, then the sort or range column.

```sql
CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at);
```

Run `EXPLAIN` again: `type` should change to `ref` or `range` and `key` should show the new index. `EXPLAIN ANALYZE` (MySQL 8.0.18 and later) and `ANALYZE SELECT` (MariaDB) execute the query and show the actual times.

On the server side, check that `innodb_buffer_pool_size` is large enough to keep the active data in memory: this is the setting that matters most. Refer to the MySQL documentation to size it according to the machine's memory.

### PostgreSQL

Log queries that exceed a threshold, in `postgresql.conf`:

```ini
log_min_duration_statement = 500
```

The value is in milliseconds. Reload with `sudo systemctl reload postgresql`.

The `pg_stat_statements` extension aggregates statistics per query. Add `shared_preload_libraries = 'pg_stat_statements'` to `postgresql.conf`, restart PostgreSQL, then:

```sql
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

SELECT calls,
       round(total_exec_time::numeric) AS total_ms,
       round(mean_exec_time::numeric, 1) AS mean_ms,
       query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
```

This ranking by cumulative time brings out both the slow query and the small query called thousands of times. Then read the actual plan:

```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10;
```

A `Seq Scan` on a large table with many discarded rows (`Rows Removed by Filter`) indicates a missing index. Create it without blocking writes:

```sql
CREATE INDEX CONCURRENTLY idx_orders_customer_created ON orders (customer_id, created_at);
```

> **Warning:** `EXPLAIN ANALYZE` actually executes the query. For an `UPDATE` or a `DELETE`, wrap it between `BEGIN;` and `ROLLBACK;`.

### Redis and Memcached

An object cache keeps the result of costly queries or computations in memory, to serve it again to subsequent HTTP requests. Redis and Memcached both fill this role; Redis also offers persistence and data structures, and is often used for sessions and queues as well.

Common rules:

- Cache what is identical for many visitors and costly to compute: menus, category lists, best sellers, counters, settings.
- Give each entry a lifetime, and invalidate it when the data changes.
- Never store visitor-specific data under a shared key.
- The cache does not replace fixing a slow query: it will fail one day, and the query will run again at the worst possible moment.

### WordPress

Versions: WordPress 6.6 and later (up to 7.1); WooCommerce 8.2 and later for High-Performance Order Storage.

**Diagnose.** Install the Query Monitor plugin. On each page, logged in as an administrator, the `Queries` panel gives the total number, the cumulative time, the duplicate queries and the component (plugin or theme) behind each one. Sort by component: a plugin responsible for most of the SQL time should be replaced or reconfigured.

**Fix loops.** A `WP_Query` that needs neither pagination nor taxonomies can be made lighter:

```php
$query = new WP_Query([
    'post_type' => 'post',
    'posts_per_page' => 6,
    'no_found_rows' => true,
    'update_post_term_cache' => false,
]);
```

`no_found_rows` avoids counting the total, which is pointless without pagination. Avoid `'posts_per_page' => -1`, `'orderby' => 'rand'` and `meta_query` on large volumes.

N+1 appears when the template calls `get_post()`, `get_userdata()` or `get_term()` in a loop over IDs. Load everything at once:

```php
$related = get_posts([
    'post_type' => 'any',
    'post__in' => $relatedIds,
    'orderby' => 'post__in',
    'posts_per_page' => count($relatedIds),
]);
```

**Lighten the options loaded on every page.** List the heaviest ones:

```sql
SELECT option_name, LENGTH(option_value) AS octets
FROM wp_options
WHERE autoload IN ('yes', 'on', 'auto', 'auto-on')
ORDER BY octets DESC
LIMIT 20;
```

Large rows left behind by uninstalled plugins can be deleted after a backup. The `Tools > Site Health` screen flags an excessive volume.

**Enable a persistent object cache.** Without it, WordPress's object cache is emptied on every page. With Redis installed on the server, add to `wp-config.php`:

```php
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
```

Install the Redis Object Cache plugin, then enable the cache in `Settings > Redis` or with `wp redis enable`. LiteSpeed Cache and W3 Total Cache offer their own object cache setting (Redis or Memcached).

For your own costly computations, use transients:

```php
$bestSellers = get_transient('best_sellers');

if ($bestSellers === false) {
    $bestSellers = get_posts([
        'post_type' => 'product',
        'meta_key' => 'total_sales',
        'orderby' => 'meta_value_num',
        'posts_per_page' => 12,
        'fields' => 'ids',
    ]);

    set_transient('best_sellers', $bestSellers, 10 * MINUTE_IN_SECONDS);
}
```

On WooCommerce, enable High-Performance Order Storage (`WooCommerce > Settings > Advanced > Features`) if the store still runs on the legacy storage.

### Laravel

Versions: Laravel 11 to 13.

**Diagnose.** Locally, Laravel Debugbar shows each page's queries and their duplicates; Telescope keeps a history of them. In production, Laravel Pulse ranks slow queries. To forbid N+1 from development onwards, in `AppServiceProvider`:

```php
public function boot(): void
{
    Model::preventLazyLoading(! $this->app->isProduction());
}
```

Any lazy loading of a relationship then throws an exception outside production.

**Fix N+1** with eager loading:

```php
$posts = Post::query()
    ->with(['author', 'category'])
    ->withCount('comments')
    ->latest()
    ->take(20)
    ->get();
```

Without `with()`, the Blade loop that displays `$post->author->name` runs one query per article.

**Add an index** with a migration:

```php
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('orders', function (Blueprint $table): void {
            $table->index(['customer_id', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::table('orders', function (Blueprint $table): void {
            $table->dropIndex(['customer_id', 'created_at']);
        });
    }
};
```

**Cache** with Redis (`CACHE_STORE=redis` in `.env`; the variable was called `CACHE_DRIVER` up to Laravel 10):

```php
$bestSellers = Cache::remember('products.best-sellers', now()->addMinutes(10), function (): Collection {
    return Product::query()->orderByDesc('sales_count')->take(12)->get();
});
```

**Log slow queries** in production, without the bindings so as not to write personal data:

```php
DB::listen(function (QueryExecuted $query): void {
    if ($query->time < 500) {
        return;
    }

    Log::warning('Slow query', ['sql' => $query->sql, 'ms' => $query->time]);
});
```

### Symfony

Versions: Symfony 6.4 and later (up to 8.1), Doctrine ORM 2.x and 3.x.

**Diagnose.** The debug toolbar shows the number of Doctrine queries and their time; the Web Profiler's Doctrine panel details them and groups identical queries.

**Fix N+1** with a fetch join in the repository:

```php
/** @return array<int, Post> */
public function findLatestWithAuthor(int $limit = 20): array
{
    return $this->createQueryBuilder('p')
        ->addSelect('a')
        ->leftJoin('p.author', 'a')
        ->orderBy('p.publishedAt', 'DESC')
        ->setMaxResults($limit)
        ->getQuery()
        ->getResult();
}
```

**Add an index** on the entity, then generate the migration (`php bin/console make:migration`):

```php
#[ORM\Entity(repositoryClass: OrderRepository::class)]
#[ORM\Table(name: 'orders')]
#[ORM\Index(name: 'idx_orders_customer_created', columns: ['customer_id', 'created_at'])]
class Order
{
}
```

**Cache** with Redis, in `config/packages/cache.yaml`:

```yaml
framework:
    cache:
        app: cache.adapter.redis
        default_redis_provider: '%env(REDIS_URL)%'
```

```php
$bestSellers = $cache->get('products.best_sellers', function (ItemInterface $item) use ($repository): array {
    $item->expiresAfter(600);

    return $repository->findBestSellers(12);
});
```

### Drupal

Versions: Drupal 10 and 11, Webprofiler (10.x and 11.x branches) and Redis 8.x-1.x modules.

The Webprofiler module lists the queries per page. Enable the core Internal Page Cache and Dynamic Page Cache modules, then the cache of each view (`Structure > Views`, edit the view, `Advanced > Other > Caching`). To move caches to Redis, install the Redis module and add to `settings.php`:

```php
$settings['redis.connection']['interface'] = 'PhpRedis';
$settings['redis.connection']['host'] = '127.0.0.1';
$settings['cache']['default'] = 'cache.backend.redis';
```

### PrestaShop

Versions: PrestaShop 8 and 9.

Enable profiling in `config/defines.inc.php` (`define('_PS_DEBUG_PROFILING_', true);`), on a copy of the site: each page then shows the time per module, the number of SQL queries, the duplicates and the slowest queries. Faceted navigation and statistics modules are the usual suspects. The server cache is configured in `Advanced Parameters > Performance`, Caching section.

### Magento

Versions: Magento Open Source and Adobe Commerce 2.4 (up to 2.4.9).

```bash
bin/magento dev:query-log:enable
bin/magento cache:flush
```

Queries are written to `var/debug/db.log`; disable with `bin/magento dev:query-log:disable`. Switch the indexers to scheduled mode and put the cache in Redis:

```bash
bin/magento indexer:set-mode schedule
bin/magento setup:config:set --cache-backend=redis --cache-backend-redis-server=127.0.0.1 --cache-backend-redis-db=0
```

### Shopify

Versions: Online Store 2.0 themes, Shopify Theme Inspector for Chrome extension, November 2026.

You have no access to the database: Shopify, like Wix, Squarespace and Webflow, manages it for you. The equivalent is Liquid rendering time. The Shopify Theme Inspector for Chrome extension shows the time spent in each section and each loop. Avoid nested loops over large collections and paginate with `{% paginate %}`.

### Next.js

Versions: Next.js 15 and 16 (App Router), Prisma 6 and 7.

With an ORM, N+1 is fixed with batch loading (`include` with Prisma) instead of one query per item in a `map`. Enable query logging in development (`new PrismaClient({ log: ['query'] })`; with Prisma 7, also pass the driver adapter, now mandatory: `new PrismaClient({ adapter, log: ['query'] })`). Generate statically, or revalidate periodically, the pages that lend themselves to it, and use a connection pool on a serverless platform. Nuxt (`swr` or `isr` route rules) and Astro (static pages by default) follow the same logic.

### Shared hosting

The slow query log is usually not accessible. Use your CMS's diagnostic tool, run `EXPLAIN` from phpMyAdmin (also accessible from Plesk and cPanel) and ask the host whether Redis or Memcached is available.

### AWS

Versions: Amazon RDS, Aurora and ElastiCache consoles, November 2026.

On Amazon RDS and Aurora, the slow query log is enabled in the parameter group from the [RDS console](https://console.aws.amazon.com/rds/) (`slow_query_log = 1`, `long_query_time`). CloudWatch Database Insights, the successor to Performance Insights, ranks queries by load. ElastiCache provides managed Valkey, Redis OSS or Memcached. Equivalents: Query Insights on Cloud SQL (Google Cloud), Query Store and Query Performance Insight on Azure.

## Common mistakes

- **Indexing each column separately**: a query that filters on two columns needs a composite index, in the right order.
- **Testing on an almost empty development database**: everything is fast there, and the execution plan differs from production.
- **Leaving the query log or profiling enabled in production** with a threshold of zero: it slows the server down and fills the disk.
- **Relying on the page cache**: uncached pages and crawlers still suffer from the slow queries.
- **Caching without invalidation**: outdated prices or stock levels shown to visitors and search engines.
- **`SELECT *` and unbounded lists**: large columns loaded for nothing, entire lists held in memory.

## Frequently asked questions

### How do I find a site's slow SQL queries?

Enable the database's slow query log, for example with a one-second threshold on MySQL, then summarize it after a few hours of real traffic with mysqldumpslow or pt-query-digest. On PostgreSQL, the pg_stat_statements extension ranks queries by cumulative time. On the application side, Query Monitor for WordPress, Laravel Debugbar or the Symfony Web Profiler show each page's queries.

### What is the N+1 problem?

The N+1 problem occurs when the code loads a list of N items in one query, then runs an extra query for each of them: the author of each article, the image of each product. The number of queries then grows with the size of the list. You fix it by loading everything at once: with() in Laravel, a fetch join in Doctrine, post__in in WordPress.

### Is a page cache enough if the database is slow?

No. The page cache hides the problem without solving it: it does not serve personalized pages such as the cart, the account or internal search, the first visit after a purge, or the deep URLs that only crawlers request. Yet Googlebot crawls these URLs in large numbers and adapts its crawl rate to the server's speed. Fix the queries, then cache.

### Should I add an index on every column?

No. An index added at random slows down writes without speeding anything up. Measure first, read the slow query's execution plan with EXPLAIN, then create the index that matches it: for a query that filters on two columns, a composite index, with the columns compared for equality first, then the sort or range column. Run EXPLAIN again to check that it is used.

## Resources

- [MySQL: The slow query log](https://dev.mysql.com/doc/refman/8.4/en/slow-query-log.html) and [EXPLAIN output format](https://dev.mysql.com/doc/refman/8.4/en/explain-output.html)
- [MariaDB: ANALYZE statement](https://mariadb.com/kb/en/analyze-statement/)
- [PostgreSQL: Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html) and [pg_stat_statements](https://www.postgresql.org/docs/current/pgstatstatements.html)
- [Google: Large site owner's guide to managing your crawl budget](https://developers.google.com/search/docs/crawling-indexing/large-site-managing-crawl-budget?hl=en)
- [Query Monitor](https://wordpress.org/plugins/query-monitor/) and [Redis Object Cache](https://wordpress.org/plugins/redis-cache/)
- [Laravel: Eager loading](https://laravel.com/docs/eloquent-relationships#eager-loading)
- [Symfony: Cache component](https://symfony.com/doc/current/cache.html)
- [Adobe Commerce: Configure Redis](https://experienceleague.adobe.com/en/docs/commerce-operations/configuration-guide/cache/redis/config-redis)

Next steps: [configure browser and server caching](https://checklist-seo-geo.com/en/performance-core-web-vitals/configure-browser-server-caching) and [optimize hosting and CDN](https://checklist-seo-geo.com/en/performance-core-web-vitals/optimize-hosting-cdn).
