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.
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.
- App to Postgres: SELECT * FROM orders LIMIT 1001SELECT * FROM orders LIMIT 100
- Postgres to App: 100 orders2100 orders
- App to Postgres: SELECT * FROM customers WHERE id = 73SELECT * FROM customers WHERE id = 7
- App to Postgres: SELECT * FROM customers WHERE id = 94SELECT * FROM customers WHERE id = 9
- App to Postgres: ...98 more round trips5...98 more round trips
- App to Postgres: Fix: WHERE id = ANY($1) or a JOIN6Fix: WHERE id = ANY($1) or a JOIN
- 1Measure
Find the costliest query by total time
- 2Explain
EXPLAIN ANALYZE to locate the slow node
- 3Change one thing
Index, rewrite or batch
- 4Re-measure
Keep it only if it really helped
- Back to step 1
- 1Network to server
Often 0.2 to 1 ms in one data centre
- 2Parse and plan
Shown as Planning Time
- 3Execute
Shown as Execution Time
- 4Send rows back
Grows with rows and columns selected
- 5App 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.
- Reads and discards skipped rows
- Deep pages get slower
- Rows shift when data changes
- Can jump to any page number
- 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.
- App to ORM: orders with customers, limit 1001orders with customers, limit 100
- ORM to Postgres: SELECT * FROM orders LIMIT 1002SELECT * FROM orders LIMIT 100
- Postgres to ORM: 100 orders, 37 distinct customer ids3100 orders, 37 distinct customer ids
- ORM to Postgres: SELECT * FROM customers WHERE id IN (...37 ids)4SELECT * FROM customers WHERE id IN (...37 ids)
- Postgres to ORM: 37 customers537 customers
- ORM to App: Orders with customer attached6Orders 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.
- 1Rewrite a slow query and compare plans~45m
- 2Detect N+1 query patterns~45m
- 3Batch queries to cut round trips~45m
- 4Measure 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
-- 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.
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.
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.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Rewrite WHERE to_char(created_at, 'YYYY-MM') = '2026-03' so it can use an index on created_at.
- 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.
- 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.