---
title: "Optimize Slow Queries"
description: "Read query plans on Managed PostgreSQL and fix sequential scans, stale statistics, unused indexes and operations that spill to disk."
url: https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/optimize-slow-queries/
product: "PostgreSQL"
section: product
last_updated: 2026-11-10
---
> For AI agents: the documentation index is at https://community.exoscale.com/llms.txt. Every page is available as markdown at `<page URL>index.md` or with `Accept: text/markdown`.

# Optimize Slow Queries

Read a query plan on Managed PostgreSQL and act on what it shows: sequential scans that should be index scans, stale planner statistics, unused indexes, and sorts or hashes that spill to disk.

Start from a list of expensive statements, built as described in
[Identify slow queries](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/identify-slow-queries/index.md).

## Get a Query Plan

`EXPLAIN` shows the plan the planner chose and its estimates, without running the statement:

```sql
EXPLAIN
SELECT id, total, created_at
FROM orders
WHERE customer_id = 4711;
```

`EXPLAIN (ANALYZE)` runs the statement and adds measured times and row counts. On PostgreSQL 18,
it also reports buffer usage by default; on older versions, write `EXPLAIN (ANALYZE, BUFFERS)`.
What matters most is the gap between estimates and reality:

```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total, created_at
FROM orders
WHERE customer_id = 4711;
```

> [!WARNING]
> `EXPLAIN (ANALYZE)` executes the statement. For `INSERT`, `UPDATE`, `DELETE` or DDL, run it in a
> transaction and roll back:
>
> ```sql
> BEGIN;
> EXPLAIN (ANALYZE) DELETE FROM orders WHERE created_at < now() - interval '2 years';
> ROLLBACK;
> ```

## Read the Plan

A plan is a tree: each indented node feeds the node above it. Here is the plan of the query above
on a 2-million-row `orders` table without an index on `customer_id`, on PostgreSQL 18:

```text
Gather  (cost=1000.00..109352.15 rows=41 width=22) (actual time=164.820..619.825 rows=49.00 loops=1)
  Workers Planned: 2
  Workers Launched: 2
  Buffers: shared hit=256 read=97691
  ->  Parallel Seq Scan on orders  (cost=0.00..108348.05 rows=17 width=22) (actual time=169.976..610.183 rows=16.33 loops=3)
        Filter: (customer_id = 4711)
        Rows Removed by Filter: 666649
        Buffers: shared hit=256 read=97691
Planning Time: 0.055 ms
Execution Time: 619.861 ms
```

| Element | Meaning |
| --- | --- |
| `cost=A..B` | Planner estimate, in arbitrary units, before the first row and for all rows. Only useful to compare plans. |
| `rows=` in `cost=...` | Rows the planner expects. |
| `actual time=A..B` | Milliseconds until the first and the last row, **per loop**. |
| `rows=` in `actual ...` | Rows actually produced, **averaged per loop**. PostgreSQL 18 prints it with two decimals. |
| `loops=N` | How many times the node ran. In a parallel node, the leader and each worker count as one loop. |
| `Filter`, `Rows Removed by Filter` | Rows read and then thrown away. |
| `Buffers: shared hit=X read=Y` | Blocks found in `shared_buffers`, and blocks read from outside it. |

Check three things, in this order:

1. **Estimated versus actual rows.** Here 41 expected, 49 returned: the statistics are fine. An
   estimate wrong by one or two orders of magnitude makes every join method above that node
   suspect. See [Keep planner statistics fresh](#keep-planner-statistics-fresh).
2. **Where the time goes.** A node's `actual time` includes its children. Subtract the children to
   get the node's own cost.
3. **How much work is discarded.** About 2 million rows read (666649 per loop, three loops) for 49
   returned: the whole table was scanned to find almost nothing.

The number of workers is capped per `Gather` node by `max_parallel_workers_per_gather` (`2` by
default) and service-wide by `max_parallel_workers` (`8`). Both are service parameters, and
`avnadmin` can also `SET` them per session.

## Fix a Sequential Scan That Should Be an Index Scan

A `Seq Scan` is the right choice for a small table or a query that returns a large share of the
rows. It is a problem when the table is large, the filter is selective, and `Rows Removed by Filter`
dwarfs the rows returned, as above. Index the filtered column without blocking writes:

```sql
CREATE INDEX CONCURRENTLY idx_orders_customer_id ON orders (customer_id);
```

The same query then uses the index:

```text
Index Scan using idx_orders_customer_id on orders  (cost=0.43..43.14 rows=41 width=22) (actual time=0.032..1.350 rows=49.00 loops=1)
  Index Cond: (customer_id = 4711)
  Index Searches: 1
  Buffers: shared hit=6 read=49
Planning Time: 0.425 ms
Execution Time: 1.384 ms
```

The condition moved from `Filter` to `Index Cond`: an `Index Cond` limits what is read, a `Filter`
discards rows already read. A node with both an `Index Cond` and a large `Rows Removed by Filter` is
a candidate for a multicolumn or partial index.

A plain `CREATE INDEX` blocks `INSERT`, `UPDATE` and `DELETE` on the table until it finishes.
`CREATE INDEX CONCURRENTLY` does not, but it scans the table twice, cannot run inside a transaction
block, and leaves an invalid index behind if it fails. Index builds write temporary files, so a low
`temp_file_limit` can make a build fail. Find invalid indexes with:

```sql
SELECT n.nspname AS schema_name, c.relname AS index_name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE NOT i.indisvalid;
```

Drop them with `DROP INDEX CONCURRENTLY` and build again. See
[Repair and rebuild indexes](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/repair-indexes/index.md).

## Choose the Right Index Type

| Index type | Typical use |
| --- | --- |
| B-tree (default) | Equality and ranges on scalar values, `ORDER BY`, unique constraints. |
| GIN | Values with many elements: `jsonb` containment, arrays, full-text search, trigram search with `pg_trgm`. |
| GiST | Ranges, geometric data, PostGIS, nearest-neighbor searches. |
| BRIN | Very large tables whose physical order follows the column, such as append-only time series. |
| Hash | Equality only. |

`pg_trgm`, `btree_gin`, `btree_gist`, `bloom` and `postgis` are extensions that `avnadmin` can
create. See
[Manage extensions](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-extensions/index.md).

### Multicolumn, Partial, Expression and Covering Indexes

```sql
-- equality column first, range or sort column second
CREATE INDEX CONCURRENTLY idx_orders_customer_created ON orders (customer_id, created_at DESC);

-- only the rows the queries look at; the query must contain status = 'pending'
CREATE INDEX CONCURRENTLY idx_orders_pending ON orders (created_at) WHERE status = 'pending';

-- the query must use the same expression, for example WHERE lower(email) = lower('USER@EXAMPLE.COM')
CREATE INDEX CONCURRENTLY idx_customers_lower_email ON customers (lower(email));

-- adds total to the index so that the query can skip the table
CREATE INDEX CONCURRENTLY idx_orders_customer_total ON orders (customer_id) INCLUDE (total);
```

A B-tree on `(a, b)` serves filters on `a` and on `a` and `b`, not filters on `b` alone. A covering
index allows an `Index Only Scan`, whose `Heap Fetches:` count should stay low; if it is high, the
visibility map is out of date and a `VACUUM` of the table fixes it.

## Drop Indexes You Do Not Use

Every index costs disk, cache space and work on every write. List indexes never scanned since the
statistics were last reset, excluding those that enforce uniqueness:

```sql
SELECT s.schemaname                                   AS schema_name,
       s.relname                                      AS table_name,
       s.indexrelname                                 AS index_name,
       s.idx_scan                                     AS index_scans,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
  AND NOT i.indisunique
  AND NOT i.indisprimary
ORDER BY pg_relation_size(s.indexrelid) DESC;
```

Check how long the counters have been accumulating:

```sql
SELECT stats_reset FROM pg_stat_database WHERE datname = current_database();
```

`NULL` means they have never been reset. An index used only by a monthly report can show
`idx_scan = 0` for weeks, and a
[read replica](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-read-replicas/index.md) keeps its own
counters: check there too if some reads go to a replica. Then:

```sql
DROP INDEX CONCURRENTLY idx_orders_status;
```

## Keep Planner Statistics Fresh

The planner's row estimates come from statistics gathered by `ANALYZE`. Autovacuum analyzes a
table once `autovacuum_analyze_threshold` (`50` rows) plus `autovacuum_analyze_scale_factor`
(`0.1`, 10% of the table) rows have changed. After a bulk load, a restore or a large update,
analyze right away:

```sql
ANALYZE orders;
```

When each table was last analyzed, and how much has changed since:

```sql
SELECT relname AS table_name, last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables
ORDER BY n_mod_since_analyze DESC
LIMIT 20;
```

If estimates for one column stay wrong, keep more samples for it:

```sql
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;
```

When two columns are correlated, the planner multiplies their selectivities and underestimates the
result. Extended statistics tell it about the correlation:

```sql
CREATE STATISTICS orders_customer_status (dependencies, ndistinct)
    ON customer_id, status
    FROM orders;
ANALYZE orders;
```

## Raise work_mem When an Operation Spills to Disk

`work_mem` is the memory one sort or hash operation may use before writing temporary files. A
spill shows in the plan:

```text
Sort  (cost=475113.33..480105.84 rows=1997002 width=121) (actual time=2161.117..2455.310 rows=1999996.00 loops=1)
  Sort Key: created_at DESC
  Sort Method: external merge  Disk: 263200kB
  Buffers: shared hit=1630 read=96320, temp read=65795 written=65878
```

`external merge  Disk:` means the sort did not fit in memory; an in-memory sort reads
`Sort Method: quicksort  Memory: 25kB`. On a `Hash` node, `Batches:` greater than 1 means the
hash table was split to disk. `temp read` and `temp written` in `Buffers` count the temporary
blocks.

`avnadmin` can raise `work_mem` for a session, a transaction or a role:

```sql
SHOW work_mem;
SET work_mem = '64MB';
ALTER ROLE reporting SET work_mem = '128MB';
```

The service-wide default is the `--pg-work-mem` flag, in MB, from `1` to `1024`:

```bash
exo dbaas update SERVICE_NAME -z ZONE -f --pg-work-mem 16
```

Parameters:

- `SERVICE_NAME`: name of the Managed PostgreSQL service, for example `my-postgresql`.
- `ZONE`: zone the service runs in, for example `ch-gva-2`.

When the flag is not set, the default is 1 MB plus 0.075% of the service RAM, capped at 32 MB.

> [!WARNING]
> `work_mem` applies per sort or hash operation, in each backend and each parallel worker. A single
> query can use several multiples of it, and so can every concurrent session. Before raising it
> service-wide, multiply it by your realistic concurrency and compare with the memory of the plan.
> Raising it for one reporting role is usually safer. See
> [Shared buffers and memory](https://community.exoscale.com/product/dbaas/service-specific/postgresql/overview/shared-buffers/index.md).

To find spilling statements without running `EXPLAIN` on each, use the `log_temp_files` parameter
or the temporary-file ranking in
[Identify slow queries](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/identify-slow-queries/index.md#find-statements-that-write-temporary-files).

## Related Pages

- [Identify slow queries](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/identify-slow-queries/index.md)
- [Check object sizes](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/check-object-sizes/index.md)
- [Repair and rebuild indexes](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/repair-indexes/index.md)
- [Manage extensions](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-extensions/index.md)
- [Using EXPLAIN in the PostgreSQL documentation](https://www.postgresql.org/docs/18/using-explain.html) ↗

