Skip to content
Visual explainer 3h to learn 4 steps

Query tuning & avoiding N+1

Rewrite slow queries and batch application queries to cut round trips.

By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.

Topic 20 of 30

In short

Most slow apps suffer from a few slow queries or from too many small ones. Measure first, rewrite or index the worst query, and replace N+1 patterns, where code runs one query per item, with a single batched query.

Explained simply

A slow app is rarely slow everywhere. Usually a few queries cause most of the pain: one that reads far too much data, or a tiny one that runs thousands of times. Tuning means finding those few and fixing them, one at a time.

Measure before you change anything. Guessing wastes time and often makes things worse. Find the query that costs the most total time, look at its plan, change one thing, and measure again. Keep the change only if the numbers really improve.

The N+1 problem is the most common cause of slow pages. Code loads a list of 100 orders with one query, then loops and loads each order's customer with its own query: 1 + 100 queries. Each query is quick, but each one waits for a network round trip.

The cure is batching: fetch all the customers in one query with a JOIN or a list of ids. One trip instead of a hundred. The same idea works for writes: insert 1,000 rows in one statement instead of 1,000 statements.

Press Play on a diagram to walk through it one step at a time.

SequenceThe N+1 problem
App
Postgres
  1. 1SELECT * FROM orders LIMIT 100
    App to Postgres: SELECT * FROM orders LIMIT 100
  2. 2100 orders
    Postgres to App: 100 orders
  3. 3SELECT * FROM customers WHERE id = 7
    App to Postgres: SELECT * FROM customers WHERE id = 7
  4. 4SELECT * FROM customers WHERE id = 9
    App to Postgres: SELECT * FROM customers WHERE id = 9
  5. 5...98 more round trips
    App to Postgres: ...98 more round trips
  6. 6Fix: WHERE id = ANY($1) or a JOIN
    App to Postgres: Fix: WHERE id = ANY($1) or a JOIN
CycleTuning loop
  1. 1
    Measure

    Find the costliest query by total time

  2. 2
    Explain

    EXPLAIN ANALYZE to locate the slow node

  3. 3
    Change one thing

    Index, rewrite or batch

  4. 4
    Re-measure

    Keep it only if it really helped

  5. Back to step 1
FlowWhere one query's time goes
  1. 1
    Network to server

    Often 0.2 to 1 ms in one data centre

  2. 2
    Parse and plan

    Shown as Planning Time

  3. 3
    Execute

    Shown as Execution Time

  4. 4
    Send rows back

    Grows with rows and columns selected

  5. 5
    App builds objects

    ORM overhead per row

In depth

Rewrites that let the planner use indexes

A condition that can use an index is called sargable. Common rewrites:

Do not wrap the column in a function. Replace date(created_at) = '2026-03-01' with a half-open range on created_at. Replace extract(year from d) = 2026 with d >= '2026-01-01' AND d < '2027-01-01'.

Match types. Comparing a text column with a number, or a bigint column with a numeric parameter, can force a cast on every row.

Replace NOT IN (subquery) with NOT EXISTS. If the subquery returns a single NULL, NOT IN returns no rows at all, and NOT EXISTS also plans better.

Select only the columns you need. SELECT * reads wide rows, pulls large TOAST values (big text or JSON stored out of line) and rules out index-only scans.

Since PostgreSQL 12, simple CTEs used once are inlined into the main query, so a CTE is no longer an automatic optimisation fence; add MATERIALIZED when you want one.

  • No functions on indexed columns
  • Half-open ranges: >= start AND < next
  • NOT EXISTS instead of NOT IN
  • Name your columns instead of SELECT *

Pagination: OFFSET versus keyset

LIMIT 20 OFFSET 100000 looks cheap but is not. Postgres must find and throw away 100,000 rows before returning 20, so each page is slower than the one before, and rows inserted between page loads can shift results so users see duplicates or miss rows.

Keyset pagination (also called seek pagination) remembers where the last page ended and asks for rows after it. With an index on (created_at, id), the query WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20 jumps straight to the right spot in the index, so page 5,000 is as fast as page 1. The id column breaks ties when two rows share a timestamp. Postgres compares the row values (created_at, id) as a pair, which a composite B-tree serves directly.

The trade-off: you cannot jump to "page 37" directly. For infinite scroll and APIs with a next cursor, that is usually fine.

CompareOFFSET vs keyset pagination
OFFSET
  • Reads and discards skipped rows
  • Deep pages get slower
  • Rows shift when data changes
  • Can jump to any page number
Keyset (seek)
  • Starts after the last seen key
  • Every page equally fast
  • Stable while rows are added
  • Only next or previous page

Detecting N+1 in real apps

N+1 hides inside ORMs (libraries that map tables to objects). Code like for order in orders: print(order.customer.name) looks innocent, but each .customer triggers a lazy load, which is one more query.

Ways to catch it: In development, log every statement (log_min_duration_statement = 0) or turn on your ORM's SQL logging (SQLAlchemy echo=True, Django's connection.queries or the Django Debug Toolbar, the Bullet gem for Rails). Count queries per request; dozens of near-identical queries with different ids is the signature. In production, pg_stat_statements shows a query with a huge calls count and a tiny mean time, such as SELECT ... FROM customers WHERE id = $1 called 3 million times an hour.

ORM fixes: eager loading. Django has select_related (JOIN for foreign keys) and prefetch_related (one extra IN query). SQLAlchemy has joinedload and selectinload. Rails has includes. Some teams add a test that fails if a page runs more than a set number of queries.

SequenceEager loading: 2 queries instead of 101
App
ORM
Postgres
  1. 1orders with customers, limit 100
    App to ORM: orders with customers, limit 100
  2. 2SELECT * FROM orders LIMIT 100
    ORM to Postgres: SELECT * FROM orders LIMIT 100
  3. 3100 orders, 37 distinct customer ids
    Postgres to ORM: 100 orders, 37 distinct customer ids
  4. 4SELECT * FROM customers WHERE id IN (...37 ids)
    ORM to Postgres: SELECT * FROM customers WHERE id IN (...37 ids)
  5. 537 customers
    Postgres to ORM: 37 customers
  6. 6Orders with customer attached
    ORM to App: Orders with customer attached

Batching writes and measuring honestly

Writes have the same round-trip cost. Inserting 10,000 rows one statement at a time, each in its own transaction, also pays for 10,000 commits, and each commit waits for the WAL to reach disk. Batch instead: a multi-row INSERT ... VALUES (...), (...), one INSERT ... SELECT FROM unnest($1::bigint[], $2::text[]) with arrays as parameters, or COPY for bulk loads, which is the fastest path. At minimum, wrap many statements in one transaction.

Measure in a fair way. Use EXPLAIN (ANALYZE, BUFFERS) for one query, and run it several times so the cache is warm for both versions. Turn on \timing in psql to see wall-clock time including the round trip. For load, pgbench can replay your own query file: pgbench -n -f query.sql -c 8 -T 30 mydb reports transactions per second and latency. Write the before and after numbers down; that record is what convinces reviewers.

  • Multi-row VALUES or unnest arrays
  • COPY for bulk loads
  • One transaction for many small writes
  • \timing and pgbench -f for before/after numbers

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Rewrite a slow query and compare plans~45m
  2. 2
    Detect N+1 query patterns~45m
  3. 3
    Batch queries to cut round trips~45m
  4. 4
    Measure before and after~45m

Key points

  • Each round trip adds network latency; 100 tiny queries can beat one slow query for slowness.
  • ORMs cause N+1 when lazy-loading related rows in a loop; use eager loading.
  • Fetch related rows in one query with a JOIN or WHERE id = ANY(array).
  • Change one thing at a time and compare plans before and after.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
-- slow: function on the column prevents index use
SELECT * FROM orders WHERE date(created_at) = '2026-03-01';

-- fast: range on the raw column can use an index
SELECT * FROM orders
WHERE created_at >= '2026-03-01' AND created_at < '2026-03-02';

-- batch instead of N+1: one query for all customers
SELECT id, name FROM customers WHERE id = ANY('{7,9,12}'::bigint[]);

Keyset pagination for an orders API

The orders API used OFFSET, and page 2,000 took 900 ms. Step 1: add an index on (created_at DESC, id DESC). Step 2: the first page has no cursor. Step 3: the response returns the created_at and id of the last row as a cursor. Step 4: the next request passes them back and the query seeks past them. Every page now takes about 1 ms regardless of depth.

sql
CREATE INDEX orders_created_id_idx ON orders (created_at DESC, id DESC);

-- first page
SELECT id, created_at, total FROM orders
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- next page: $1, $2 = created_at and id of the last row shown
SELECT id, created_at, total FROM orders
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 20;

Fixing an N+1 in Python with one batched query

A report loops over 500 order ids and runs a query for each order's items, taking 1.5 seconds mostly in round trips. Step 1: collect the ids. Step 2: send them as one array parameter with = ANY(%s). Step 3: group the rows in Python. Result: one round trip and about 40 ms. psycopg turns a Python list into a Postgres array automatically.

python
import psycopg
from collections import defaultdict

with psycopg.connect("dbname=shop") as conn:
    order_ids = [r[0] for r in conn.execute(
        "SELECT id FROM orders WHERE created_at >= now() - interval '1 day'")]
    rows = conn.execute(
        "SELECT order_id, sku, qty FROM order_items WHERE order_id = ANY(%s)",
        (order_ids,)).fetchall()

items = defaultdict(list)
for order_id, sku, qty in rows:
    items[order_id].append((sku, qty))

Quick reference

  • Half-open date range: created_at >= '2026-03-01' AND created_at < '2026-03-02'
  • NOT EXISTS instead of NOT IN when the subquery column can be NULL
  • Keyset paging: WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC
  • WHERE id = ANY($1) with an array parameter replaces N separate lookups
  • COPY or multi-row INSERT for bulk writes; wrap small writes in one transaction
  • \timing in psql shows wall-clock time per statement
  • pgbench -n -f query.sql -c 8 -T 30 mydb load-test your own query

Common mistakes

  • Optimising by guesswork without measuring.
  • Fixing N+1 with a cache instead of a better query.
  • Changing several things at once and not knowing which helped.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1pg_stat_statements shows SELECT * FROM users WHERE id = $1 with 2 million calls per hour and 0.05 ms mean time. What does this most likely mean?

Question 2

2Why does LIMIT 20 OFFSET 200000 get slow?

Question 3

3WHERE id NOT IN (SELECT manager_id FROM employees) returns no rows, though you expected many. Why?

Question 4

4Which change is most likely to make WHERE extract(year from created_at) = 2026 use an index on created_at?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Rewrite WHERE to_char(created_at, 'YYYY-MM') = '2026-03' so it can use an index on created_at.

  2. Exercise 2medium

    Insert 3 products in a single statement and return their new ids, then do the same for any number of products using arrays as parameters.

  3. Exercise 3hard

    A page lists 50 customers with their latest order date and order count, and runs 101 queries. Write one query that returns everything.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a JOIN always better than two queries?
Not always. A JOIN repeats the parent columns for every child row, so for one parent with many large children, two queries (parents, then children WHERE parent_id = ANY(...)) can transfer less data. Both are far better than N+1.
Should I fix N+1 with a cache?
Fix the query first. A cache hides the problem until it expires, adds stale-data bugs, and the batched query is usually fast enough on its own.
How do I count rows quickly on a huge table?
An exact count(*) must read the table or an index. If an estimate is enough, read reltuples from pg_class, which is updated by VACUUM and ANALYZE.

Go deeper

ShareXLinkedInWhatsApp