A table big enough to feel slow
ShopKart's 15 orders are too few to notice speed. We generated 500,000 random orders:
-- A bigger table to see indexes in action: 500,000 orders
CREATE TABLE big_orders AS
SELECT g AS order_id,
(random() * 49999)::int + 1 AS customer_id,
DATE '2024-01-01' + (random() * 900)::int AS order_date,
(ARRAY['PLACED', 'DELIVERED', 'CANCELLED'])[1 + (random() * 2)::int] AS status,
round((random() * 5000)::numeric, 2) AS amount
FROM generate_series(1, 500000) AS g;
ANALYZE big_orders; -- collect statistics for the plannerWithout an index: a full scan
EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id = 42;Gather
Workers Planned: 2
-> Parallel Seq Scan on big_orders
Filter: (customer_id = 42)Seq Scan = read the whole table, checking each row. PostgreSQL even used 2 extra workers in parallel. On our laptop this took about 10 ms; on a billion-row table, minutes.
How an index works
🌳Root
1–25,000 → left · 25,001–50,000 → right
🔀Branch pages
Narrow the range: 1–100, 101–200, …
🍃Leaf pages
customer_id 42 → row locations (page 1203 row 7, page 8810 row 2, …)
📦Table (heap)
Fetch only those rows
Like a phone book: you don't read every name, you open near “R” and narrow down. A few page reads instead of thousands.
CREATE INDEX idx_big_orders_customer ON big_orders (customer_id);
CREATE INDEX idx_big_orders_date ON big_orders (order_date);EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id = 42;Bitmap Heap Scan on big_orders
Recheck Cond: (customer_id = 42)
-> Bitmap Index Scan on idx_big_orders_customer
Index Cond: (customer_id = 42)Now it uses idx_big_orders_customer. Measured on our laptop: about 0.05 ms instead of ~10 ms: roughly 200× faster. (A Bitmap scan collects matching row locations first, then reads the table pages in order.)
Sargable vs non-sargable
-- ❌ A function on the column hides it from the index
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_orders WHERE EXTRACT(YEAR FROM order_date) = 2025 AND EXTRACT(MONTH FROM order_date) = 3;Finalize Aggregate
-> Gather
Workers Planned: 2
-> Partial Aggregate
-> Parallel Seq Scan on big_orders
Filter: ((EXTRACT(year FROM order_date) = '2025'::numeric) AND (EXTRACT(month FROM order_date) = '3'::numeric))-- ✅ Same question as a range on the raw column: the index can be used
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_orders WHERE order_date >= '2025-03-01' AND order_date < '2025-04-01';Aggregate
-> Bitmap Heap Scan on big_orders
Recheck Cond: ((order_date >= '2025-03-01'::date) AND (order_date < '2025-04-01'::date))
-> Bitmap Index Scan on idx_big_orders_date
Index Cond: ((order_date >= '2025-03-01'::date) AND (order_date < '2025-04-01'::date))Both count orders in March 2025 (we checked they return the same number). The first hides order_date inside EXTRACT, so the index on order_date can't be used: full scan. The second compares the raw column with a range: index used.
| ❌ Not sargable | ✅ Sargable |
|---|---|
| WHERE EXTRACT(YEAR FROM d) = 2025 | WHERE d >= '2025-01-01' AND d < '2026-01-01' |
| WHERE LOWER(email) = '[email protected]' | Index on LOWER(email) (expression index), or store emails lowercase |
| WHERE amount * 1.18 > 1000 | WHERE amount > 1000 / 1.18 |
| WHERE name LIKE '%kart' | WHERE name LIKE 'Shop%' (prefix) |
Reading a join plan
EXPLAIN (COSTS OFF)
SELECT c.name, SUM(oi.quantity * oi.unit_price)
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.name;HashAggregate
Group Key: c.name
-> Hash Join
Hash Cond: (o.customer_id = c.customer_id)
-> Hash Join
Hash Cond: (oi.order_id = o.order_id)
-> Seq Scan on order_items oi
-> Hash
-> Seq Scan on orders o
-> Hash
-> Seq Scan on customers cOn tiny tables PostgreSQL picks hash joins. Know the three join algorithms:
| Algorithm | How | Best when |
|---|---|---|
| Nested loop | For each row on one side, look up matches on the other | One side small, other side indexed |
| Hash join | Build a hash table from the smaller side, probe with the other | Large unsorted equality joins |
| Merge join | Walk two sorted inputs together | Both sides already sorted on the key |
Index types and tips
- Composite index
(customer_id, order_date): works for filters on customer_id, or customer_id + order_date (leftmost prefix), not order_date alone. - Covering index: includes every column a query needs, so the table isn't touched (Index Only Scan).
- Unique index: enforces uniqueness (PRIMARY KEY and UNIQUE create one).
- Clustered vs non-clustered (SQL Server/MySQL): a clustered index is the table's physical order (one per table); non-clustered indexes point to rows.
- Low-cardinality columns (status with 3 values) rarely benefit alone. Partial indexes help:
WHERE status = 'PLACED'. - Run
ANALYZEso the planner has fresh statistics.
Row storage vs column storage
Row store (PostgreSQL, MySQL)
Each row's values together
Great: fetch/insert one order fast
Slow: SUM(amount) over 1B rows reads every column
Column store (Snowflake, BigQuery, Parquet/Delta)
Each column's values together, compressed
Great: SUM(amount) reads only one column
Skips files using min/max stats (data skipping)
Query-writing habits that keep things fast
- Select only the columns you need (no
SELECT *in pipelines). - Filter early, on indexed or clustered columns, with sargable conditions.
- Join on keys with matching types; aggregate before joining when you can.
- Use
EXISTSinstead ofCOUNT(*) > 0to check existence. - Prefer UNION ALL over UNION when duplicates are impossible or acceptable.
- Check
EXPLAIN ANALYZEbefore and after any change.
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is an index and what are its trade-offs?Fresher+
Q2Clustered vs non-clustered index?1–3 yrs+
Q3How do you investigate a slow query?1–3 yrs+
Q4Why isn't my index being used?1–3 yrs+
Q5How does performance tuning differ in a columnar warehouse?3+ yrs+
Key takeaways
- ✓Indexes turn full scans into quick lookups: 200× faster in our test.
- ✓EXPLAIN tells you what the database is really doing.
- ✓Write sargable conditions so indexes can be used.
- ✓Next: designing tables well with normalization and star schemas.
Frequently asked questions
What is an index in SQL?
A separate sorted structure (usually a B-tree) that maps column values to the rows that have them, like the index at the back of a book. It lets the database jump to matching rows instead of scanning the whole table.
Why not index every column?
Every index takes disk space and must be updated on every INSERT, UPDATE and DELETE, slowing writes. Index the columns you filter, join and sort on often.
What does EXPLAIN do?
It shows the plan the database will use: which tables it scans, whether it uses indexes, which join method, and estimated costs. EXPLAIN ANALYZE actually runs the query and adds real times and row counts.
What is a sargable query?
One whose conditions can use an index (Search ARGument ABLE). Wrapping the column in a function (EXTRACT(YEAR FROM date) = 2025) usually isn't sargable; a range on the raw column (date >= ... AND date < ...) is.
Do warehouses like Snowflake and Databricks use indexes?
Mostly not in the B-tree sense. They store data in columns and skip whole files or micro-partitions using min/max statistics, clustering and partitioning. The idea (avoid reading what you don't need) is the same.
🧠 Quick check: indexes and performance
1. A query filters on customer_id with no index. The plan shows...
2. Which condition can use an index on order_date?
3. Indexes make which operations slower?
4. An index on (customer_id, order_date) helps WHERE...
Checking your access…