Index Strategy — Database

Design indexes for a set of queries, not one per query. A composite index is usually only used from its leftmost column (leftmost prefix): (a, b, c) serves a…

Every time a query got slow, Sunset Coffee's team added one index. Over time the orders table piled up indexes that overlap, every INSERT got heavier, and some of the indexes were never read at all.

Index strategy turns that around: choose a set of indexes for all of your app's important queries at once, instead of adding one index every time a query is slow. Picture the spice racks in Sunset Coffee's kitchen. Each rack helps the cooks grab spices faster, but every time a delivery arrives, every rack has to be tidied again. A good kitchen has a few racks that many dishes use, not one rack per dish. The racks are indexes, the dishes are queries, and the deliveries are INSERTs.

A reminder: leftmost prefix

In the Indexes & Performance lesson you built a composite index, an index made of two or more columns. It's sorted by the leftmost column first, so the index (a, b, c) can only be used when the WHERE uses columns from the left without skipping:

WHERE Uses the index (a, b, c)?
a = 1, a = 1 AND b = 2, a = 1 AND b = 2 AND c = 3 Yes
b = 2, c = 3, b = 2 AND c = 3 Usually not, the first column is skipped

The order you write things in the WHERE doesn't matter: b = 2 AND a = 1 still uses that index. What decides is which columns are mentioned. There is an exception: SQLite (after ANALYZE), MySQL 8.0.13 and later, and PostgreSQL 18 have skip scan, which can still use the index when the first column is skipped. Skip scan only helps when the first column has few distinct values, so do not design indexes around it. The exercise uses the plain leftmost prefix rule. In this lesson we use that rule to design indexes for several queries at once.

Three queries, one set of indexes

The orders table in the Lab is the same as in the Indexes & Performance lesson: 20,000 orders, Siti (customer_id 2) has 100, and 400 are still 'pending'. These three queries run most often at Sunset Coffee:

-- 1. Siti's order history
SELECT * FROM orders WHERE customer_id = 2 ORDER BY created_at DESC;

-- 2. Siti's spending summary: dates and totals only
SELECT created_at, total FROM orders WHERE customer_id = 2 ORDER BY created_at DESC;

-- 3. The admin queue: orders not processed yet
SELECT * FROM orders WHERE status = 'pending' ORDER BY created_at;

For each query, note three things: the columns searched with =, the column for a range or ORDER BY, and the columns the SELECT takes. Queries 1 and 2 both search customer_id and then sort by created_at, so they can share one index.

Covering index: one index for two queries

A covering index already holds every column a query needs, so the database never has to open the table. Add total at the end:

CREATE INDEX idx_orders_customer_date_total ON orders(customer_id, created_at, total);
query 1:  SEARCH orders USING INDEX idx_orders_customer_date_total (customer_id=?)
query 2:  SEARCH orders USING COVERING INDEX idx_orders_customer_date_total (customer_id=?)

Columns after a range aren't used for searching

The admin also looks for one customer's pending orders since a certain date: WHERE customer_id = 2 AND created_at >= '2026-10-01' AND status = 'pending'. Compare two column orders:

(customer_id, created_at, status)   SEARCH ... (customer_id=? AND created_at>?)
(customer_id, status, created_at)   SEARCH ... (customer_id=? AND status=? AND created_at>?)

Once the index meets a range column (created_at >=), the columns after it can't be used to jump any further, only to filter. So the order is: every = column first, then one range or ORDER BY column at the very end.

Duplicate indexes and unused indexes

In the Lab, switch on (customer_id) together with (customer_id, created_at). None of the three plans mention idx_orders_customer any more: queries 1 and 2 prefer the composite index, because it's already sorted by date. So which query still uses (customer_id)? None. (customer_id) has become a prefix of the composite index, so it only takes 188 KB and gets written on every INSERT, without ever being read. Drop an index like that.

In PostgreSQL, find unused indexes through pg_stat_user_indexes: the idx_scan column counts how often each index has been used. One that is still at 0 after weeks in production is a candidate to drop.

Partial index for a rare value

Query 3 looks for 400 of 20,000 rows. You know the partial index from the Indexes & Performance lesson:

CREATE INDEX idx_orders_pending ON orders(created_at) WHERE status = 'pending';
-- query 3:  SCAN orders USING INDEX idx_orders_pending

In the Lab it's only 3 pages (12 KB), while a plain index on status is 75 pages (300 KB) and still has to sort by itself. The query has to state the same condition, status = 'pending', otherwise this index isn't used. The same pattern fits a column that only holds TRUE/FALSE: a plain index doesn't help much, but a partial index for the rare value you look for often, for example WHERE is_active = false, is small and fast.

The price: measure, don't guess

These are the sizes the Lab measures with PRAGMA page_count (1 page = 4 KB) for 20,000 orders:

In the database Size
the orders table 636 KB
(customer_id) 188 KB
(customer_id, created_at) 404 KB
(customer_id, created_at, total) 468 KB
(created_at) WHERE status = 'pending' 12 KB

A composite index is almost as big as the table itself. And every INSERT writes to the table plus every index. The best set for the three queries above is just two indexes: (customer_id, created_at, total) and the pending partial index, 480 KB, and all three queries run without reading the whole table and without sorting by themselves. In the Lab you can time 5,000 INSERTs with 0 and with 3 indexes yourself.

📌 An index on a function's result

In the EXPLAIN lesson you saw that a column wrapped in a function can't use a plain index. If the query really always uses that function, the index can be built on the function's result (an expression index):

CREATE INDEX idx_customers_email_lower ON customers(lower(email));

SELECT * FROM customers WHERE lower(email) = '[email protected]';
-- SEARCH customers USING INDEX idx_customers_email_lower (<expr>=?)

Without that index, the plan is SCAN customers. PostgreSQL writes it the same way, MySQL (since 8.0.13) with double brackets: ((lower(email))). The expression in the query has to match the one in the index exactly.

⚠️ Too many indexes, or columns in the wrong order

TL;DR: Design indexes for a set of queries, not one per query. A composite index is usually only used from its leftmost column (leftmost prefix): (a, b, c) serves a, a + b, a + b + c, but not b or c alone, except through skip scan. Put every = column first, then one range or ORDER BY column. A covering index holds every column needed, so one index (customer_id, created_at, total) can serve both the history and the summary without opening the table. A partial index suits a rare value, boolean columns included. Duplicate or never-used indexes only slow writes and take room, so measure and drop them.

⚡ Design for a set of queries

Guess first: an index holds two or more columns, for example (customer_id, created_at). What is it called?

A composite index. It's sorted column by column from the left, so it's only used starting from its leftmost column (the leftmost prefix).

Meaning: Choose a set of indexes for all your important queries at once, not one index every time a query is slow. (a, b, c) serves a, a + b, a + b + c, but not b or c alone.

In the exercise, the order of queryCols doesn't matter, and the return value is a boolean true/false, not text.

⚡ Covering index

Write:

CREATE INDEX idx_orders_customer_date_total ON orders(customer_id, created_at, total);

Meaning: This index holds every column Siti's spending summary needs, so the table isn't opened at all. The order history and the summary share the same index.

⚡ = columns first, the range last

Write:

(customer_id, created_at, status)   SEARCH ... (customer_id=? AND created_at>?)
(customer_id, status, created_at)   SEARCH ... (customer_id=? AND status=? AND created_at>?)

Meaning: After a range column, the next columns only filter, they aren't used to jump. Duplicate or never-used indexes only slow writes, so measure and drop them.

What you will learn