StackPractices
advanced By Mathias Paulenko

Complete Guide to SQL Query Optimization

Find and fix slow SQL queries: read EXPLAIN plans, index the right way, kill N+1 queries, and apply partitioning, pooling, and caching on PostgreSQL and MySQL.

Introduction

Slow queries are the most common database performance problem — and one of the most fixable. A single unoptimized query can hold locks for seconds, pin a CPU core at 100%, or turn a 50 ms page into a five-second timeout. Most of them collapse to a handful of causes: missing or wrong indexes, plans the planner built on stale statistics, N+1 loops hiding in application code, and work the database shouldn’t be doing at all.

This guide walks the full loop: how to find the queries that actually hurt, how to read an EXPLAIN plan without guessing, and how to match the fix to the bottleneck — indexes, rewrites, materialized views, partitioning, pooling, or caching. Every example runs on PostgreSQL and MySQL (or names the dialect where they differ). If you only need the triage-sheet version, keep the database query tuning checklist open next to this guide — this file is the deeper theory behind those steps.

The Optimization Loop

Optimization is a measurement cycle, not a checklist you run once:

  1. Find the queries that cost the most total time — not the ones that look slow.
  2. Read their execution plan.
  3. Apply the smallest change that fixes the real bottleneck.
  4. Re-measure. If it’s still slow, go back to step 2.
flowchart diagram: Slow page or alert

The rest of this guide walks each step in order.

Finding Slow Queries

You can’t optimize what you haven’t measured. Two tools do the discovery work: cumulative statistics — which queries cost the most over time — and the slow query log, which records every execution that crossed a threshold.

PostgreSQL: pg_stat_statements

pg_stat_statements is the most important optimization tool PostgreSQL ships. It tracks calls, total time, mean time, and rows for every normalized query, so you can sort by what actually costs your database time.

-- Requires shared_preload_libraries = 'pg_stat_statements' in postgresql.conf,
-- then once: CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Top 10 by total time — optimize these first
SELECT query, calls, total_exec_time, mean_exec_time, rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Sort by total_exec_time, not mean_exec_time. A 500 ms query called 10,000 times a day costs more than a 10-second report that runs weekly. mean_exec_time matters when you already know a query is hot.

For what’s slow right now — a query holding locks or blocking others — look at live activity:

SELECT pid, now() - query_start AS duration, state, query
FROM pg_stat_activity
WHERE state = 'active'
  AND now() - query_start > interval '1 second'
  AND query NOT LIKE '%pg_stat_activity%'
ORDER BY duration DESC;

MySQL: slow query log and Performance Schema

-- Enable at runtime (persist in my.cnf: slow_query_log=1, long_query_time=1)
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;

-- Which normalized statements cost the most time
SELECT DIGEST_TEXT, COUNT_STAR,
       SUM_TIMER_WAIT/1e12 AS total_sec,
       AVG_TIMER_WAIT/1e12 AS avg_sec
FROM performance_schema.events_statements_summary_by_digest
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 10;

long_query_time = 1 logs everything slower than a second; drop it to 0.1 for a day when hunting web-request latency. On managed services (AWS RDS, Cloud SQL), enable both pg_stat_statements and the slow log through parameter groups — the same queries work.

When to Optimize — and When Not To

Optimize when:

  • A query ranks high by total time in pg_stat_statements or the slow log.
  • An endpoint’s p95 latency is dominated by database time (check your APM first — the bottleneck is often elsewhere).
  • A production plan shows Seq Scan on a large, frequently-queried table.
  • ORM code iterates a relationship inside a loop — the classic N+1 smell.

Do not optimize when:

  • The table holds a few thousand rows. Sequential scans are fine — often faster — at that size, and the planner knows it.
  • The query runs once a day in a batch job nobody waits for.
  • You haven’t measured. Tuning by intuition adds indexes that tax writes for zero read benefit.
  • The fix costs more than the problem. A materialized view needing 15-minute refreshes for a report someone reads monthly is complexity, not optimization.

Reading EXPLAIN Plans

EXPLAIN shows the plan the database chose; EXPLAIN ANALYZE (PostgreSQL, and MySQL 8.0.18+) actually executes it and shows real timings. Always tune against ANALYZE output — estimated plans lie, actual plans don’t.

PostgreSQL EXPLAIN

-- Plan only, no execution
EXPLAIN SELECT * FROM users WHERE email = 'alice@example.com';

-- Executes and shows real timing
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';

-- With I/O stats — the most useful form
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM users WHERE email = 'alice@example.com';

Read plans inside-out — the innermost node executes first:

NodeWhat it meansWhen to worry
Seq ScanReads every rowBad on large tables in hot paths; fine for small ones
Index ScanIndex lookup + table fetchThe standard healthy plan
Index Only ScanIndex alone answers the queryBest case — needs a covering index
Bitmap ScanBitmap of matches, batched fetchFine for moderate selectivity
Nested LoopPer outer row, scan innerFine when the outer side is small
Hash JoinHash table on smaller inputEfficient for large unsorted joins
Merge JoinBoth inputs sorted, mergedEfficient for pre-sorted data
SortIn-memory or disk sortExpensive if it spills to disk
LimitStops after N rowsCheap — but watch a Sort above it
EXPLAIN ANALYZE
SELECT u.name, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.status = 'active'
GROUP BY u.id, u.name
ORDER BY order_count DESC
LIMIT 10;

-- Reading bottom-up:
-- Limit
--   Sort
--     HashAggregate
--       Hash Join
--         Seq Scan on users u   (Filter: status = 'active')
--         Hash
--           Seq Scan on orders o

-- Three problems visible:
-- 1. Seq Scan on users — no index on status
-- 2. Seq Scan on orders — no index on user_id
-- 3. Sort before Limit — an index could have supplied the order

Two numbers in ANALYZE output matter more than node names: actual time and rows. If the planner estimated 200 rows and found 50,000, the plan rests on stale statistics — run ANALYZE users; before adding any index. Wrong estimates cause most “the planner ignored my index” complaints.

MySQL EXPLAIN

EXPLAIN SELECT * FROM users WHERE email = 'alice@example.com';
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';  -- 8.0.18+
EXPLAIN FORMAT=JSON SELECT * FROM users WHERE email = 'alice@example.com';
type valueMeaning
const, eq_refSingle-row match via primary/unique key — ideal
ref, rangeIndex lookup or range scan — fine
indexFull index scan — tolerable
ALLFull table scan — the problem child

Watch Extra for Using temporary (temp table materialization) and Using filesort (a sort no index covers). Both are fixable with the right index or a rewrite.

Index Strategies

Indexes are the biggest-impact fix and the most-abused one. Three patterns cover most real cases; for the full catalog of index types — B-Tree vs GIN vs GiST vs BRIN — see the indexing strategies guide.

Covering indexes

A covering index holds every column the query reads, so the engine never touches the table:

-- PostgreSQL: INCLUDE adds non-key columns to the leaf
CREATE INDEX idx_users_email_name ON users (email) INCLUDE (name, id);

-- Now Index Only Scan — no table fetch
SELECT id, name FROM users WHERE email = 'alice@example.com';

-- MySQL: all needed columns go in the index itself
CREATE INDEX idx_users_email_name ON users (email, name, id);

Partial indexes

Index only the rows that matter:

-- PostgreSQL: index only active users
CREATE INDEX idx_active_users_email ON users (email) WHERE status = 'active';

SELECT * FROM users WHERE status = 'active' AND email = 'alice@example.com';

-- MySQL: emulate with a generated column
ALTER TABLE users ADD COLUMN is_active TINYINT
  GENERATED ALWAYS AS (IF(status='active',1,NULL)) STORED;
CREATE INDEX idx_active_users ON users (is_active, email);

Partial indexes shine on skewed data — if 90% of rows are status = 'archived', indexing only the 10% that get queried keeps the index small and hot.

Composite index order

Column order decides what the index can serve. Working rule: equality columns first, then the sort column, then the range column.

-- Query: WHERE status = 'active' AND age > 18 ORDER BY created_at DESC
CREATE INDEX idx_users_status_created_age ON users (status, created_at DESC, age);

-- Serves:
-- WHERE status = 'active'                                    -- equality prefix
-- WHERE status = 'active' ORDER BY created_at DESC           -- sort covered, no filesort
-- WHERE status = 'active' AND age > 18 ORDER BY created_at   -- age applied as residual filter

One honest caveat: age > 18 after the sort column is a residual filter — the index still eliminates the sort but can’t seek directly into the matching ages. If the range is highly selective, put it before the sort column and accept the filesort. There’s no universal answer; measure both orders with EXPLAIN ANALYZE.

Join Optimization

Joins go wrong two ways: missing indexes on join columns, and filtering too late.

-- Index the join columns on both sides
CREATE INDEX idx_orders_user_id ON orders (user_id);
CREATE INDEX idx_users_status ON users (status) INCLUDE (name);

-- Filter early: narrow rows before joining, not after
SELECT c.name, p.title, a.content
FROM comments c
JOIN posts p ON c.post_id = p.id
JOIN authors a ON p.author_id = a.id
WHERE c.created_at > '2026-01-01';

CREATE INDEX idx_comments_created_post ON comments (created_at, post_id);
CREATE INDEX idx_authors_id ON authors (id) INCLUDE (name);

The three join algorithms map to three situations:

  • Nested loop: indexed lookups on the inner side — optimal when the outer side is small (hundreds of rows).
  • Hash join: builds a hash table on the smaller input — optimal for large, unsorted inputs.
  • Merge join: merges two sorted inputs — optimal when both sides arrive sorted on the join key.
-- PostgreSQL lets you toggle join methods for testing (never in production)
SET enable_nestloop = off;
SET enable_hashjoin = on;
SET enable_mergejoin = on;

If the planner picks nested loop on a join returning millions of rows, the row estimates are probably wrong — update statistics before forcing a different plan.

N+1 Query Detection

The N+1 pattern kills more web endpoints than any missing index: one query for the list, then one per item. A page showing 100 users and their order counts issues 101 queries — and latency multiplies.

# Bad: 1 + N queries — with 1,000 users, 1,001 round trips
import sqlite3

conn = sqlite3.connect("app.db")
users = conn.execute("SELECT id, name FROM users").fetchall()

for user in users:
    orders = conn.execute(
        "SELECT * FROM orders WHERE user_id = ?", (user[0],)
    ).fetchall()
    print(f"{user[1]}: {len(orders)} orders")

# Good: one JOIN aggregates everything
results = conn.execute("""
    SELECT u.id, u.name, COUNT(o.id) AS order_count
    FROM users u
    LEFT JOIN orders o ON u.id = o.user_id
    GROUP BY u.id, u.name
""").fetchall()

for row in results:
    print(f"{row[1]}: {row[2]} orders")

In ORMs it’s the same bug wearing a nicer outfit — lazy-loaded relationships inside loops. SQLAlchemy gives two fixes:

from sqlalchemy.orm import Session, joinedload, selectinload

# Bad: lazy load = one query per user.orders access
with Session(engine) as session:
    users = session.query(User).all()
    for user in users:
        print(len(user.orders))

# Good: joinedload — one query with LEFT JOIN
users = session.query(User).options(joinedload(User.orders)).all()

# Good: selectinload — two queries total, batched IN list
users = session.query(User).options(selectinload(User.orders)).all()

Use joinedload for one-to-one or few related rows; selectinload for one-to-many — it avoids JOIN row-multiplication. Django’s select_related/prefetch_related and Rails’ includes map to the same two strategies. The eager loading pattern covers the general approach, and the GraphQL N+1 detection recipe shows how it surfaces in resolvers.

Detection tip: enable query logging in development — a page emitting dozens of same-shaped queries is the tell.

Query Rewriting

Most “the index doesn’t work” bugs are really “the query can’t use the index” bugs:

-- Function on the indexed column defeats the index
SELECT * FROM users WHERE LOWER(email) = 'alice@example.com';

-- Fix: functional index, or normalize on write
CREATE INDEX idx_users_email_lower ON users (LOWER(email));

-- Implicit type mismatch (order_number is VARCHAR)
SELECT * FROM orders WHERE order_number = 12345;    -- bad
SELECT * FROM orders WHERE order_number = '12345';  -- good

-- Leading wildcard can't seek a B-tree
SELECT * FROM products WHERE name LIKE '%laptop%';

-- PostgreSQL: a trigram index makes it searchable
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_products_name_trgm ON products USING gin (name gin_trgm_ops);

-- DATE() on the column breaks the index — rewrite as a range
SELECT * FROM orders WHERE DATE(created_at) = '2026-01-15';               -- bad
SELECT * FROM orders
WHERE created_at >= '2026-01-15' AND created_at < '2026-01-16';           -- good

-- OR across separately-indexed columns → UNION ALL
SELECT * FROM users
WHERE email = 'alice@example.com' OR phone = '555-1234';                  -- may seq-scan
SELECT * FROM users WHERE email = 'alice@example.com'
UNION ALL
SELECT * FROM users
WHERE phone = '555-1234' AND email != 'alice@example.com';

Two rewrites worth knowing that get used less than they should:

-- EXISTS beats IN for large subqueries — stops at the first match
SELECT * FROM customers c
WHERE EXISTS (
    SELECT 1 FROM orders o
    WHERE o.customer_id = c.id AND o.total > 1000
);

-- Correlated subquery per row → one JOIN with aggregation
SELECT u.name, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;

Materialized Views

When an aggregation is expensive and a few minutes of staleness is acceptable, pre-compute it:

CREATE MATERIALIZED VIEW order_summary AS
SELECT u.id AS user_id, u.name,
       COUNT(o.id) AS total_orders,
       SUM(o.total) AS total_spent,
       MAX(o.created_at) AS last_order_date
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;

CREATE UNIQUE INDEX idx_order_summary_user_id ON order_summary (user_id);
CREATE INDEX idx_order_summary_total ON order_summary (total_spent DESC);

-- Fast — reads pre-computed data
SELECT * FROM order_summary ORDER BY total_spent DESC LIMIT 10;

-- Refresh without blocking reads (requires the unique index)
REFRESH MATERIALIZED VIEW CONCURRENTLY order_summary;

MySQL has no materialized views — the standard workaround is a summary table plus a scheduled event:

CREATE TABLE order_summary AS
SELECT u.id AS user_id, u.name,
       COUNT(o.id) AS total_orders,
       SUM(o.total) AS total_spent,
       MAX(o.created_at) AS last_order_date
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;

-- Requires SET GLOBAL event_scheduler = ON (or event_scheduler=ON in my.cnf)
DELIMITER //
CREATE EVENT refresh_order_summary
ON SCHEDULE EVERY 1 HOUR
DO BEGIN
  TRUNCATE TABLE order_summary;
  INSERT INTO order_summary
  SELECT u.id, u.name, COUNT(o.id), SUM(o.total), MAX(o.created_at)
  FROM users u
  LEFT JOIN orders o ON u.id = o.user_id
  GROUP BY u.id, u.name;
END //
DELIMITER ;

Multi-statement event bodies need BEGIN ... END — without it, the CREATE EVENT fails on the second statement. The materialized views recipe goes deeper on refresh strategies and invalidation. For the architectural side — when a materialized view is the right trade-off and how it feeds CQRS read models — see the Materialized View Pattern.

Partitioning

Partitioning shrinks what each query scans — partition pruning drops irrelevant partitions from the plan entirely. It’s a schema-level fix for tables that outgrew indexing alone: roughly 50M+ rows, or workloads where almost every query filters on one column.

-- PostgreSQL: range partition by month
CREATE TABLE orders (
  id BIGSERIAL,
  user_id BIGINT NOT NULL,
  total DECIMAL(10,2),
  status VARCHAR(20),
  created_at TIMESTAMP NOT NULL
) PARTITION BY RANGE (created_at);

CREATE TABLE orders_2026_01 PARTITION OF orders
  FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE orders_2026_02 PARTITION OF orders
  FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');

-- Only scans the February partition
SELECT * FROM orders
WHERE created_at >= '2026-02-01' AND created_at < '2026-03-01';
-- List partitioning by category
CREATE TABLE products (
  id BIGSERIAL,
  name VARCHAR(255),
  category VARCHAR(50) NOT NULL,
  price DECIMAL(10,2)
) PARTITION BY LIST (category);

CREATE TABLE products_electronics PARTITION OF products
  FOR VALUES IN ('electronics', 'computers');
CREATE TABLE products_other PARTITION OF products DEFAULT;

-- Only scans products_electronics
SELECT * FROM products WHERE category = 'electronics';

Partition on the column your queries actually filter by — almost always created_at in practice. Partitioning by a column nobody filters on buys you maintenance cost with zero pruning benefit. When the table is large because one node can’t hold it anymore, that’s a different problem — see the database sharding guide. For huge append-only tables, a PostgreSQL BRIN index often gets you most of the win at a fraction of the complexity.

Connection Pooling

Opening a database connection costs a TCP handshake, authentication, and memory allocation — tens of milliseconds before your query even runs. A pool amortizes that across requests.

# Bad: new connection per call — 30-60 ms overhead every time
import psycopg2

def get_user(user_id):
    conn = psycopg2.connect("dbname=app user=postgres")
    cur = conn.cursor()
    cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
    user = cur.fetchone()
    cur.close()
    conn.close()
    return user

# Good: shared pool
from psycopg2 import pool

connection_pool = pool.ThreadedConnectionPool(
    minconn=5, maxconn=20,
    dbname="app", user="postgres",
    password="password", host="localhost",
)

def get_user(user_id):
    conn = connection_pool.getconn()
    try:
        cur = conn.cursor()
        cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
        return cur.fetchone()
    finally:
        connection_pool.putconn(conn)

For async workloads, asyncpg’s pool is the standard choice:

import asyncpg
import asyncio

async def main():
    pool = await asyncpg.create_pool(
        host="localhost", database="app",
        user="postgres", password="password",
        min_size=5, max_size=20,
    )
    async with pool.acquire() as conn:
        user = await conn.fetchrow(
            "SELECT * FROM users WHERE id = $1", 123
        )
        print(user)
    await pool.close()

asyncio.run(main())

Pool sizing: 5–20 connections per app instance is a sane starting point, and the fleet total must stay under max_connections (default 100 in PostgreSQL). When instances outgrow that, run PgBouncer in transaction mode — it funnels thousands of client connections onto a few dozen real ones. The connection pooling recipe has per-framework configurations.

Query Caching

Caching happens at three layers — the buffer pool, the OS page cache, and the application. They’re complementary, not interchangeable.

-- Buffer cache hit ratio per table (low = cache misses)
CREATE EXTENSION IF NOT EXISTS pg_prewarm;

SELECT relname, heap_blks_read, heap_blks_hit,
       ROUND(100.0 * heap_blks_hit /
             NULLIF(heap_blks_read + heap_blks_hit, 0), 1) AS hit_pct
FROM pg_statio_user_tables
ORDER BY hit_pct ASC NULLS LAST;

-- Warm a table into buffer cache after a restart
SELECT pg_prewarm('users');

Below ~95% hit ratio on hot tables, more shared_buffers usually beats more query tuning.

At the application layer, cache query results in Redis with a TTL:

import json
import hashlib
import redis
import psycopg2

r = redis.Redis(host="localhost", port=6379)
db = psycopg2.connect("dbname=app user=postgres host=localhost")

def cached_query(query: str, params: tuple, ttl: int = 300):
    cache_key = f"q:{hashlib.md5((query + str(params)).encode()).hexdigest()}"
    cached = r.get(cache_key)
    if cached:
        return json.loads(cached)

    cur = db.cursor()
    cur.execute(query, params)
    results = cur.fetchall()
    r.setex(cache_key, ttl, json.dumps(results, default=str))
    return results

users = cached_query(
    "SELECT id, name FROM users WHERE status = %s",
    ("active",), ttl=60,
)

The hard part is never GET/SET — it’s invalidation. Cache queries whose results can safely be stale for the TTL (leaderboards, catalog pages, counts), and don’t cache anything a user must see fresh: inventory, payments, permissions. If every caller gets a different result, caching buys you a Redis bill and nothing else.

Putting It Together: A Worked Example

A sales dashboard query takes 45 seconds. The tables: orders (50M rows), order_items (200M rows), customers (2M rows).

SELECT c.name, SUM(oi.line_total) AS revenue, COUNT(DISTINCT o.id) AS orders
FROM customers c
JOIN orders o ON c.id = o.customer_id
JOIN order_items oi ON o.id = oi.order_id
WHERE o.created_at >= '2026-01-01' AND o.status = 'completed'
GROUP BY c.name
ORDER BY revenue DESC LIMIT 20;

-- Plan: 2 seq scans + hash joins + sort → 45s

Fix 1 — indexes. A partial composite index on the filtered columns plus the FK:

CREATE INDEX idx_orders_date_status ON orders (created_at, status)
  WHERE status = 'completed';
CREATE INDEX idx_order_items_order ON order_items (order_id);
-- Plan: index scans + merge join → 8s

Fix 2 — materialized view. Indexes got 5×, but 8 s is still slow for a dashboard. Pre-aggregate:

CREATE MATERIALIZED VIEW mv_daily_sales AS
SELECT DATE(o.created_at) AS sale_date, c.name AS customer,
       SUM(oi.line_total) AS revenue, COUNT(DISTINCT o.id) AS orders
FROM customers c
JOIN orders o ON c.id = o.customer_id
JOIN order_items oi ON o.id = oi.order_id
WHERE o.status = 'completed'
GROUP BY DATE(o.created_at), c.name;

CREATE UNIQUE INDEX idx_mv_daily ON mv_daily_sales (sale_date, customer);
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_daily_sales;

SELECT customer, SUM(revenue) AS total, SUM(orders) AS order_count
FROM mv_daily_sales
WHERE sale_date >= '2026-01-01'
GROUP BY customer
ORDER BY total DESC LIMIT 20;
-- Plan: scan on ~1M-row MV + aggregate → 200ms

Fix 3 — pooling. The app opened a fresh connection per dashboard load, adding ~50 ms to every request. PgBouncer in transaction mode cut that to ~2 ms:

[databases]
production = host=10.0.0.1 port=5432 dbname=app
[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 25

The sequence matters: indexes first (cheap, helps everything), then pre-computation (removes the expensive work entirely), then operational fixes (pooling, partitioning for refresh speed). Each fix was verified with EXPLAIN ANALYZE before moving on — 45 s to ~200 ms plus negligible connection overhead.

Best Practices

  • Rank by total time, not mean time. A 500 ms query called 10,000 times a day costs more than a 10-second report run weekly — pg_stat_statements exists to answer exactly that question.
  • Index foreign keys and join columns by default. Missing join indexes cause more slow queries than every exotic issue combined.
  • Keep statistics fresh. Run ANALYZE after bulk loads and schema changes; most “ignored index” mysteries are stale estimates, not planner bugs.
  • Avoid over-indexing. Every index taxes writes and disk. Audit pg_stat_user_indexes quarterly — idx_scan = 0 means drop candidates.
  • Measure before and after. EXPLAIN ANALYZE the slow query, apply one fix, re-run it. Change two things at once and you can’t attribute the win.
  • Partition when a table outgrows its working set, not because it’s large. Ten million rows that fit in RAM don’t need partitions.

Common Mistakes

  • Optimizing before measuring. Guessing at the bottleneck fixes the wrong thing — usually by adding an index nobody needed.
  • SELECT * on wide tables. Defeats covering indexes and drags TOAST’d columns (JSON blobs, text fields) across the wire.
  • Using SELECT DISTINCT to hide a join problem. If DISTINCT “fixes” duplicate rows, the join was wrong — you’ve made it slower and buried the bug.
  • COUNT(*) on huge tables in hot paths. Use pg_class.reltuples estimates or maintain a counter table.
  • Functions on indexed columns (LOWER(email), DATE(created_at)) when a range predicate or normalized column would do.
  • Trusting query hints. MySQL FORCE INDEX goes stale as data grows — the real fix is statistics or schema. PostgreSQL has no planner hints, by design.
  • Adding an index for every slow query. Sometimes the answer is a materialized view, a rewrite, or accepting that 2 s on a nightly report is fine.

See Also

Further Reading

Frequently Asked Questions

How do I read an EXPLAIN plan?

Inside-out and bottom-up — the innermost node runs first. In PostgreSQL, look for Seq Scan on large tables (usually needs an index), Index Scan (good), and Index Only Scan (best). In MySQL, check type — ALL is a full scan, ref/eq_ref means index lookup — and watch Extra for Using filesort or Using temporary. Then compare estimated rows against actual; a big gap means stale statistics, so run ANALYZE before adding indexes.

What is the N+1 query problem?

One query fetches a list, then N more fetch related data per item — 100 users plus their orders becomes 101 queries. Fix it with a JOIN, eager loading (joinedload/selectinload in SQLAlchemy, select_related/prefetch_related in Django, includes in Rails), or a DataLoader in GraphQL. Turn on query logging in development — a page emitting dozens of same-shaped queries is the tell.

When should I use a materialized view vs a regular view?

Materialized when the underlying query is expensive — multi-table aggregations, dashboards — and minutes-old data is acceptable: results are stored physically and read instantly. Regular when you need real-time data or the query is cheap: it's just saved SQL that re-runs every call. Refresh on a schedule, or REFRESH ... CONCURRENTLY to avoid blocking reads.

Why does my query use a sequential scan when I have an index?

Usually because it should. When a query returns more than ~5–10% of a table, sequential reads beat random index lookups — the planner made the right call. It can also mean stale statistics (run ANALYZE) or an index that doesn't match the query shape: wrong column order, or a function wrapping the column.

How many indexes is too many?

There's no magic number — each index slows writes and eats disk. Audit pg_stat_user_indexes quarterly: idx_scan = 0 flags drop candidates (check it's not backing a UNIQUE constraint first). Composite indexes covering several query shapes usually beat one index per column.

Should I always use connection pooling?

Yes, in production — each new connection costs a TCP handshake plus authentication, and per-request connections stack latency fast. Use PgBouncer (external, works with any client), asyncpg.create_pool, or HikariCP for Java. Start at 5–20 connections per app instance and keep the fleet total under max_connections.