SQL · Module 11 · Lesson 52 min read

Writing Fast Queries

1. Select only what you need

SELECT * reads and transfers every column (including large text/JSON). List the columns; this can also enable index-only scans.

2. Keep filters "sargable" (index-friendly)

Don't wrap indexed columns in functions or math:

❌ Slow (can't use the index)✅ Fast
WHERE date_trunc('month', spent_on) = '2026-11-01'WHERE spent_on >= '2026-11-01' AND spent_on < '2026-12-01'
WHERE EXTRACT(year FROM created_at) = 2026WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01'
WHERE amount * 1.13 > 1000WHERE amount > 1000 / 1.13
WHERE lower(email) = … (without an expression index)an expression index, or store emails lowercased
WHERE title ILIKE '%x%' on huge tablestrigram index / full-text search

3. Avoid the N+1 query problem

App code that runs 1 query for a list, then 1 query per item (100 items → 101 queries). Instead: one JOIN, IN (…), or json_agg to fetch everything at once.

4. Filter early, aggregate late

  • Put conditions in WHERE, not HAVING, when they don't need aggregates
  • Pre-aggregate before joining (avoids fan-out)

5. EXISTS instead of COUNT for "is there any?"

EXISTS (SELECT 1 …) stops at the first match; count(*) > 0 counts everything.

6. Batch your writes

One INSERT with many rows, or COPY, instead of thousands of single INSERTs; wrap batches in a transaction.

7. Be careful with

  • OFFSET 100000 → keyset pagination (next lesson)
  • DISTINCT hiding a bad join
  • OR across different columns (may prevent index use → sometimes split into UNION ALL)
  • Functions called per row in SELECT on large results
  • NOT IN with subqueries → NOT EXISTS

8. Measure, don't guess

EXPLAIN ANALYZE, pg_stat_statements (Unit 14), and test with realistic data volumes.

Example

SQL
CREATE TABLE logs AS
SELECT g AS id, (g % 2000) + 1 AS user_id,
       TIMESTAMPTZ '2026-01-01' + (g || ' minutes')::interval AS created_at,
       'event ' || g AS message
FROM generate_series(1, 300000) g;
CREATE INDEX idx_logs_created ON logs (created_at);
ANALYZE logs;

-- ❌ Not sargable: function on the indexed column → Seq Scan
EXPLAIN SELECT count(*) FROM logs WHERE date_trunc('day', created_at) = '2026-03-01';

-- ✅ Sargable range → Index (Only) Scan
EXPLAIN SELECT count(*) FROM logs
WHERE created_at >= '2026-03-01' AND created_at < '2026-03-02';

-- ✅ EXISTS stops at the first match
SELECT EXISTS (SELECT 1 FROM logs WHERE user_id = 7) AS has_logs;

-- ❌ N+1 pattern (what an app loop does):
--   SELECT id, name FROM users;                       -- 1 query
--   SELECT * FROM expenses WHERE user_id = 1;         -- + 1 per user...
--   SELECT * FROM expenses WHERE user_id = 2; ...
-- ✅ One query returning everything the page needs
SELECT u.id, u.name,
       COALESCE(json_agg(json_build_object('title', e.title, 'amount', e.amount)
                ORDER BY e.spent_on DESC) FILTER (WHERE e.id IS NOT NULL), '[]') AS expenses
FROM users u
LEFT JOIN expenses e ON e.user_id = u.id
GROUP BY u.id
ORDER BY u.id;

-- ✅ Select only needed columns (enables index-only scans)
CREATE INDEX idx_logs_user_created ON logs (user_id, created_at);
VACUUM ANALYZE logs;
EXPLAIN SELECT created_at FROM logs WHERE user_id = 7 ORDER BY created_at DESC LIMIT 10;
-- Index Only Scan Backward using idx_logs_user_created

DROP TABLE logs;