Skip to content

Query optimization means getting the same result while the database reads fewer rows. To improve SQL performance, read the query plan, the database's own description of how it will run the query, and find the step that reads far more rows than it returns. The usual fixes are an index on the filter column, a filter that index can use, a shorter column list, and filtering before you join or aggregate.

Each fix is shown below as a before and after plan from PostgreSQL 16.13: real output, with psql's header and footer trimmed and no timings. More guides are in the SQL hub.

How to see the query plan

PostgreSQL's planner, also called the optimizer, works out the possible ways to scan each table and join the results, estimates a cost for each, and runs the cheapest. EXPLAIN prints that plan without running the query. EXPLAIN ANALYZE runs the query and adds real row counts, so roll the transaction back if the statement changes data. The options used below hide cost estimates and timings.

The test tables

The data is 20,000 customers and 500,000 orders across 2024 and 2025.

create table customers (
    customer_id integer primary key,
    email       text,
    signup_date date
);

create table orders (
    order_id    integer primary key,
    customer_id integer,
    ordered_at  timestamp,
    status      text,
    amount      numeric(10, 2)
);

insert into customers
select g, 'user' || g || '@example.com', date '2023-01-01' + (g - 1) / 20
from generate_series(1, 20000) as g;

select setseed(0.42);

insert into orders
select g,
       1 + floor(random() * 20000)::integer,
       timestamp '2024-01-01' + random() * interval '730 days',
       case g % 10 when 0 then 'cancelled' when 1 then 'pending' else 'completed' end,
       round((random() * 500)::numeric, 2)
from generate_series(1, 500000) as g;

set default_statistics_target = 2000;
vacuum analyze;

set max_parallel_workers_per_gather = 0;

ANALYZE collects the planner's statistics, normally from a random sample, so plans can change between runs. A statistics target of 2000 made it read every row, and the last line turns off parallel query. Both settings are for repeatable examples, not production.

Read a query plan: sequential scan versus index scan

A plan is a tree. Scan nodes at the bottom read tables, and the nodes above them join, aggregate, or sort. A lookup by primary key:

explain (costs off)
select order_id, amount from orders where order_id = 250000;

Index Scan using orders_pkey on orders
  Index Cond: (order_id = 250000)

An Index Scan finds matching entries in an index and fetches those rows from the table. PostgreSQL creates an index for every primary key, here orders_pkey. Now filter on a column with no index:

explain (analyze, costs off, timing off, summary off, buffers off)
select order_id, ordered_at, amount from orders where customer_id = 4242;

Seq Scan on orders (actual rows=15 loops=1)
  Filter: (customer_id = 4242)
  Rows Removed by Filter: 499985

A Seq Scan (sequential scan) reads every row and checks the filter on each. rows counts the rows a node outputs, not the rows it reads: this node read 500,000 to return 15. loops is how many times the node ran, and above 1, rows is the average per loop.

Add an index on the column you filter by

Index the column and rerun:

create index orders_customer_id_idx on orders (customer_id);

explain (costs off)
select order_id, ordered_at, amount from orders where customer_id = 4242;

Bitmap Heap Scan on orders
  Recheck Cond: (customer_id = 4242)
  ->  Bitmap Index Scan on orders_customer_id_idx
        Index Cond: (customer_id = 4242)

A Bitmap Heap Scan is a two-step plan. The Bitmap Index Scan under it collects the locations of matching rows from the index, and the upper node fetches only those rows from the table, in physical order.

An index is not always used. where customer_id > 1000 still gets a Seq Scan, because it keeps 474,963 of the 500,000 rows and fetching rows through an index costs more per row than reading them in sequence. Indexes also slow writes, since PostgreSQL updates every index when rows change, and its documentation advises removing seldom-used ones. SQL Server adds clustered indexes, which store the table's rows in key order: see clustered vs non-clustered indexes.

Keep functions off the indexed column

An index on ordered_at holds ordered_at values. A filter on ordered_at::date computes a different value for each row, so the index does not apply:

create index orders_ordered_at_idx on orders (ordered_at);

explain (costs off)
select order_id, amount from orders where ordered_at::date = date '2025-03-14';

Seq Scan on orders
  Filter: ((ordered_at)::date = '2025-03-14'::date)

Compare the bare column with a range instead:

explain (costs off)
select order_id, amount from orders
where ordered_at >= '2025-03-14' and ordered_at < '2025-03-15';

Bitmap Heap Scan on orders
  Recheck Cond: ((ordered_at >= '2025-03-14 00:00:00'::timestamp without time zone) AND (ordered_at < '2025-03-15 00:00:00'::timestamp without time zone))
  ->  Bitmap Index Scan on orders_ordered_at_idx
        Index Cond: ((ordered_at >= '2025-03-14 00:00:00'::timestamp without time zone) AND (ordered_at < '2025-03-15 00:00:00'::timestamp without time zone))

Both filters return the same 645 rows. If you cannot rewrite a filter, PostgreSQL can index the expression: an index on lower(email) turned a Seq Scan for a filter on lower(email) into a bitmap scan.

Select only the columns you need

That query selected order_id and amount, which are not in the index, so PostgreSQL visited the table. SELECT * gets the same plan. If you need only the timestamps:

explain (analyze, costs off, timing off, summary off, buffers off)
select ordered_at from orders
where ordered_at >= '2025-03-14' and ordered_at < '2025-03-15';

Index Only Scan using orders_ordered_at_idx on orders (actual rows=645 loops=1)
  Index Cond: ((ordered_at >= '2025-03-14 00:00:00'::timestamp without time zone) AND (ordered_at < '2025-03-15 00:00:00'::timestamp without time zone))
  Heap Fetches: 0

An Index Only Scan answers the query from the index alone: Heap Fetches: 0 means it never read the table. Every column the query references must be in the index, and the table must be vacuumed, because PostgreSQL still checks the table for recently changed rows. A covering index adds extra columns through INCLUDE to make this possible.

Filter before you join or aggregate

PostgreSQL already pushes a plain WHERE condition down to the table scan: a join filtered at the end and the same join over a pre-filtered subquery got identical plans here. (For grouped queries, see HAVING vs. WHERE.) It did not push a filter on one table into an aggregate over another. This query totals every customer's orders, then keeps the 20 who signed up on one day:

explain (costs off)
select c.customer_id, t.total_amount
from customers c
join (
    select customer_id, sum(amount) as total_amount
    from orders
    group by customer_id
) t on t.customer_id = c.customer_id
where c.signup_date = date '2025-06-30';

Hash Join
  Hash Cond: (orders.customer_id = c.customer_id)
  ->  HashAggregate
        Group Key: orders.customer_id
        ->  Seq Scan on orders
  ->  Hash
        ->  Seq Scan on customers c
              Filter: (signup_date = '2025-06-30'::date)

A Hash Join loads one input into an in-memory hash table and looks up each row of the other input in it. The HashAggregate is the GROUP BY: with an unfiltered Seq Scan under it, it totals all 500,000 orders for a join that keeps 20 customers. Join first, then aggregate:

explain (analyze, costs off, timing off, summary off, buffers off)
select c.customer_id, sum(o.amount) as total_amount
from customers c
join orders o on o.customer_id = c.customer_id
where c.signup_date = date '2025-06-30'
group by c.customer_id;

HashAggregate (actual rows=20 loops=1)
  Group Key: c.customer_id
  Batches: 1  Memory Usage: 24kB
  ->  Nested Loop (actual rows=485 loops=1)
        ->  Seq Scan on customers c (actual rows=20 loops=1)
              Filter: (signup_date = '2025-06-30'::date)
              Rows Removed by Filter: 19980
        ->  Bitmap Heap Scan on orders o (actual rows=24 loops=20)
              Recheck Cond: (c.customer_id = customer_id)
              Heap Blocks: exact=482
              ->  Bitmap Index Scan on orders_customer_id_idx (actual rows=24 loops=20)
                    Index Cond: (customer_id = c.customer_id)

A Nested Loop runs its inner side once per outer row: 20 customers, each an index lookup averaging 24 orders. The aggregate receives 485 rows, not 500,000, and the result is the same. Writing the subquery as a common table expression gave the first plan again.

Use EXISTS when a join would multiply rows

To list customers with at least one completed order, a join returns one row per order and DISTINCT collapses them:

explain (analyze, costs off, timing off, summary off, buffers off)
select distinct c.customer_id, c.email
from customers c
join orders o on o.customer_id = c.customer_id
where o.status = 'completed';

HashAggregate (actual rows=20000 loops=1)
  Group Key: c.customer_id, c.email
  Batches: 1  Memory Usage: 2321kB
  ->  Hash Join (actual rows=400000 loops=1)
        Hash Cond: (o.customer_id = c.customer_id)
        ->  Seq Scan on orders o (actual rows=400000 loops=1)
              Filter: (status = 'completed'::text)
              Rows Removed by Filter: 100000
        ->  Hash (actual rows=20000 loops=1)
              Buckets: 32768  Batches: 1  Memory Usage: 1378kB
              ->  Seq Scan on customers c (actual rows=20000 loops=1)

EXISTS asks the question directly:

explain (analyze, costs off, timing off, summary off, buffers off)
select c.customer_id, c.email
from customers c
where exists (
    select 1
    from orders o
    where o.customer_id = c.customer_id
      and o.status = 'completed'
);

Nested Loop Semi Join (actual rows=20000 loops=1)
  ->  Seq Scan on customers c (actual rows=20000 loops=1)
  ->  Index Scan using orders_customer_id_idx on orders o (actual rows=1 loops=20000)
        Index Cond: (customer_id = c.customer_id)
        Filter: (status = 'completed'::text)
        Rows Removed by Filter: 0

This is a semi join: each customer comes out once, and the index scan on orders averaged one row per customer, because an EXISTS subquery generally runs only until it finds a row. No 400,000-row intermediate result is built, and both queries return the same 20,000 customers. IN (SELECT ...) got the identical plan, so the real choice is semi join versus join plus DISTINCT. The joins guide covers one-to-many joins.

Symptoms, likely causes, and fixes

What the plan showsLikely causeFix
Seq Scan with Rows Removed by Filter near the table sizeNo index on the filter columnIndex that column
Seq Scan with an indexed column inside a function or castThe index holds the column, not the expressionFilter the bare column by range, or index the expression
Bitmap Heap Scan when only an indexed column is neededSELECT * or extra columnsSelect fewer columns, or add a covering index
Aggregate over a whole table, under a join that keeps few rowsFilter applied after a GROUP BY subqueryJoin and filter first, then aggregate
Join output far larger than the result, under HashAggregate or UniqueOne-to-many join plus DISTINCTUse EXISTS
Scan under Limit returns far more rows than the limitLarge OFFSET: skipped rows are still computedFilter on the sort key instead
Estimated rows far from actual rowsOut-of-date statisticsRun ANALYZE

See also SQL anti-patterns that hurt dashboard performance.

BigQuery and Snowflake do not use these indexes

  • BigQuery. Google's documentation says BigQuery stores tables in columnar format, that indexes are neither needed nor offered for batch analytics, and that partitioning or clustering is used instead. See BigQuery SQL best practices.
  • Snowflake. Snowflake divides tables into micro-partitions, stores columns separately inside them, and keeps each column's value range so a query can skip micro-partitions that cannot match. CREATE INDEX is for hybrid tables, its row-based table type. See partitioning strategies in Snowflake and BigQuery.

Frequently Asked Questions

What is query optimization in SQL?

Query optimization is finding the cheapest way to produce a query's result. The database's planner does most of it by comparing possible plans. Your part is to give it better options, such as an index or a filter it can use.

Why is PostgreSQL not using my index?

Usually because the filter wraps the column in a function or cast, the filter matches so much of the table that a sequential scan is cheaper, or the column is not the leading column of a multicolumn index. Out-of-date statistics can also mislead the planner.

Can an index speed up a LIKE filter?

Only when the pattern is anchored at the start, such as LIKE 'user4242@%'. A pattern that begins with a wildcard cannot use a B-tree index. Unless the database uses the C locale, the index also needs the text_pattern_ops operator class.

What tools find slow queries in PostgreSQL?

The pg_stat_statements module records execution statistics for the statements a server runs, and the log_min_duration_statement setting logs statements that run longer than a threshold.

Primary sources and further reading

The SQL was run and the vendor pages were read on November 22, 2026.