Writing Fast Queries
Writing fast queries in SQL means writing conditions and shapes that let the planner use indexes and read as little data as possible. Two queries can return exactly the same rows while one reads 36 pages and the other 128, because of how a single condition is written. In this lesson, we will learn what makes a condition sargable (usable with an index), why functions and casts on indexed columns hide the index, what SELECT * costs, whether EXISTS, IN or a join is faster, and how to run a huge update without blocking everyone.
In One Minute
- A sargable condition compares the bare column with a value:
paid_on >= '2025-06-01'. - Wrapping the column in a function or cast, like
EXTRACT(YEAR FROM paid_on)orstudent_id::text, hides the index. SELECT *reads and sends every column; name the columns you need.EXISTS,INand joins usually get the same plan in PostgreSQL; write the clearest one.- Change millions of rows in batches, so locks and transactions stay short.
Sargable Conditions
A condition is sargable ("Search ARGument ABLE") when the database can look its value up in an index. That requires the indexed column to stand alone on one side of the comparison. The examples use the generated big_payments table (20,000 rows, 128 pages) with an index on paid_on. Payments in June 2025, written with functions on the column:
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_paid_idx ON big_payments (paid_on);
ANALYZE big_payments;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT count(*) FROM big_payments
WHERE EXTRACT(YEAR FROM paid_on) = 2025 AND EXTRACT(MONTH FROM paid_on) = 6;CREATE TABLE
INSERT 0 20000
CREATE INDEX
ANALYZE
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
Buffers: shared hit=128
-> Seq Scan on big_payments (actual rows=810.00 loops=1)
Filter: ((EXTRACT(year FROM paid_on) = '2025'::numeric) AND (EXTRACT(month FROM paid_on) = '6'::numeric))
Rows Removed by Filter: 19190
Buffers: shared hit=128
Planning:
Buffers: shared hit=21 read=1
(8 rows)Explanation: The index stores paid_on values, not years and months. The planner can't search it for EXTRACT(...) = 6, so it scans all 128 pages and computes the expression for every row. The same question, written against the bare column:
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_paid_idx ON big_payments (paid_on);
ANALYZE big_payments;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT count(*) FROM big_payments
WHERE paid_on >= '2025-06-01' AND paid_on < '2025-07-01';CREATE TABLE
INSERT 0 20000
CREATE INDEX
ANALYZE
QUERY PLAN
------------------------------------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
Buffers: shared hit=33 read=3
-> Bitmap Heap Scan on big_payments (actual rows=810.00 loops=1)
Recheck Cond: ((paid_on >= '2025-06-01'::date) AND (paid_on < '2025-07-01'::date))
Heap Blocks: exact=33
Buffers: shared hit=33 read=3
-> Bitmap Index Scan on big_payments_paid_idx (actual rows=810.00 loops=1)
Index Cond: ((paid_on >= '2025-06-01'::date) AND (paid_on < '2025-07-01'::date))
Index Searches: 1
Buffers: shared read=3
Planning:
Buffers: shared hit=17 read=2
(12 rows)Explanation: Same 810 rows, but now a Bitmap Index Scan finds exactly June's range: 36 pages instead of 128. The half-open range (>= the first day, < the next month's first day) is also correct for timestamps, as IN and BETWEEN showed.
| Not sargable | Sargable rewrite |
|---|---|
EXTRACT(YEAR FROM paid_on) = 2025 | paid_on >= '2025-01-01' AND paid_on < '2026-01-01' |
student_id + 0 = 1234 | student_id = 1234 |
student_id::text = '1234' | student_id = 1234 |
lower(email) = 'x' (plain index on email) | an expression index on lower(email) |
amount_usd * 2 > 500 | amount_usd > 250 |
Casts and Mismatched Types
A cast on the column side hides the index just like a function. Comparing student_id::text = '1234' scans every row; comparing student_id = 1234 uses the index. The same trap hides in joins between columns of different types, such as an INTEGER id joined to a TEXT copy of it. Keep matching columns the same type.
The Cost of SELECT *
SELECT * reads, converts and sends every column, including ones you don't use. On wide tables, that's more data from disk, more memory, and more network traffic. It also prevents index-only scans, because the index rarely contains every column, and it breaks silently when someone adds a column, as SELECT showed. Name the columns.
EXISTS, IN or a Join?
In PostgreSQL, EXISTS, IN and an equivalent join usually produce the same plan, because the planner rewrites them into the same "semi-join":
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
EXPLAIN (COSTS OFF)
SELECT * FROM students AS s
WHERE EXISTS (SELECT 1 FROM big_payments AS p WHERE p.student_id = s.student_id);
EXPLAIN (COSTS OFF)
SELECT * FROM students AS s
WHERE s.student_id IN (SELECT student_id FROM big_payments);CREATE TABLE
INSERT 0 20000
ANALYZE
QUERY PLAN
----------------------------------------------
Hash Join
Hash Cond: (s.student_id = p.student_id)
-> Seq Scan on students s
-> Hash
-> HashAggregate
Group Key: p.student_id
-> Seq Scan on big_payments p
(7 rows)
QUERY PLAN
-------------------------------------------------------
Hash Join
Hash Cond: (s.student_id = big_payments.student_id)
-> Seq Scan on students s
-> Hash
-> HashAggregate
Group Key: big_payments.student_id
-> Seq Scan on big_payments
(7 rows)Explanation: Both become a Hash Join against the distinct student_id values. So choose by meaning and safety, not speed: EXISTS and IN are interchangeable, but NOT IN breaks on NULLs, so prefer NOT EXISTS (as EXISTS showed). Other databases optimize these differently; check the plan rather than relying on folklore.
Batching Big Updates
One UPDATE of millions of rows holds row locks on all of them until it commits, and creates millions of dead row versions at once. Other sessions wait, and the table bloats. Instead, update in batches of a few thousand rows, committing each:
-- repeat until it updates 0 rows
UPDATE big_payments
SET method = 'card'
WHERE payment_id IN (
SELECT payment_id FROM big_payments
WHERE method IS NULL
LIMIT 5000
);Each batch locks only 5,000 rows, for a moment, and autovacuum can clean up between batches.
Common Mistakes
Functions on indexed columns. WHERE date_trunc('month', paid_on) = ... can't use an index on paid_on; use a range.
SELECT * in application code. It reads more and breaks when columns change.
Rewriting IN as EXISTS for speed. In PostgreSQL they usually plan the same; rewrite only NOT IN.
Huge single-statement updates. Batch them.
Interview Corner
What does sargable mean?
A condition the database can satisfy using an index seek, typically a bare indexed column compared with a value. Wrapping the column in a function, cast or arithmetic makes it non-sargable.
Why can WHERE YEAR(order_date) = 2025 be slow?
The function hides the column from its index, so every row must be read and the function computed. A range on the bare column, order_date >= '2025-01-01' AND order_date < '2026-01-01', can use the index.
Is EXISTS faster than IN?
In PostgreSQL they're usually rewritten into the same semi-join plan. The important difference is correctness: NOT IN returns nothing if the subquery contains NULL, while NOT EXISTS doesn't.
Practice
Challenge: This query can't use an index on student_id: WHERE student_id::text = '1234'. Rewrite it to be sargable, add the index, and show the plan with buffers.
Show solution
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
CREATE INDEX big_payments_student_idx ON big_payments (student_id);
ANALYZE big_payments;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT count(*) FROM big_payments WHERE student_id = 1234;CREATE TABLE
INSERT 0 20000
CREATE INDEX
ANALYZE
QUERY PLAN
--------------------------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
Buffers: shared hit=4 read=2
-> Bitmap Heap Scan on big_payments (actual rows=4.00 loops=1)
Recheck Cond: (student_id = 1234)
Heap Blocks: exact=4
Buffers: shared hit=4 read=2
-> Bitmap Index Scan on big_payments_student_idx (actual rows=4.00 loops=1)
Index Cond: (student_id = 1234)
Index Searches: 1
Buffers: shared read=2
Planning:
Buffers: shared hit=19 read=2
(12 rows)Comparing the integer column with an integer lets the index find the 4 rows in about 6 pages. The cast version reads all 128.
Key Takeaways
| Instead of | Write |
|---|---|
EXTRACT(YEAR FROM paid_on) = 2025 | paid_on >= '2025-01-01' AND paid_on < '2026-01-01' |
student_id::text = '1234' | student_id = 1234 |
SELECT * | SELECT payment_id, amount_usd |
One huge UPDATE | Repeated UPDATE ... WHERE id IN (SELECT ... LIMIT 5000) |
Was this tutorial helpful?