15 min read
Database indexes and EXPLAIN ANALYZE
In one sentence: An index is a separate, sorted list of some columns, with the location of each row: PostgreSQL goes straight to what you’re looking for without reading the whole table. EXPLAIN ANALYZE shows which path it took and what it cost.
What you will learn
- Explain what an index is and why a B-tree reaches any value in a few steps.
- Read an EXPLAIN ANALYZE plan: Seq Scan or Index Scan, cost, rows, time and Buffers.
- Choose the columns of a composite index and their order, knowing what it costs.
- Paginate by cursor in SQL with an index, and explain why OFFSET gets slow.
Before you start, read: 06-migrations.md
The problem
Section titled “The problem”Imagine the shop already has 100,000 orders. The phone app asks for the ten newest, GET /v2/orders, and your API, the one from lesson 6, “Migrations”, asks PostgreSQL for all of them to keep ten in Node, as in Phase 4.
Cutting in SQL, with LIMIT 10, fixes the trip: only ten rows leave the DatabaseA program that stores data in an organized way and lets you search and change it quickly, even when many people use it at once. The backend keeps in it whatever needs to last.Go to definition. But inside, PostgreSQL still reads the 100,000 orders to find out which are the newest. On every request, and with twice the orders, twice the work.
Here you see what PostgreSQL does inside, with EXPLAIN ANALYZE, and you give it a direct path: an index.
The analogy
Section titled “The analogy”The analogy
You look up “photosynthesis” in a 600-page biology book. Without an index, you leaf through the whole thing. With one, you go to the back: the words are in alphabetical order, each with its pages. You find “photosynthesis, p. 212” and open it there.
The index isn’t the book: it’s a separate, sorted list that points to where each thing is.
Where the analogy breaks down
- A book’s index is written once. A database’s is kept up to date with every row that comes in, changes or goes.
- A table can have several indexes, one for each way of searching, and each one takes up disk space.
- To read half the book, the index saves nothing. PostgreSQL doesn’t use it either if it’s going to read a large part of the table.
How it really works
Section titled “How it really works”The outputs are from PostgreSQL 18.6, with the 100,000 orders you’ll generate in Try it. The times change on every run: what matters is how many times bigger one is than another.
An index is a separate, sorted list
Section titled “An index is a separate, sorted list”This is the lesson’s index, in a new MigrationA file with a change to a database’s tables, such as adding a column, that is applied only once and in order, without deleting the data already there. The database itself records in a table which ones have already been applied.Go to definition, 003-orders-index.sql:
CREATE INDEX orders_by_date ON orders (created_at DESC, id DESC);CREATE INDEX orders_by_datecreates an index with that name.ON orders (created_at DESC, id DESC)gives the table and the columns, in order: from the newest order to the oldest and, with the same date, the higher id first.
In the table, rows go wherever there’s room, in no useful order. The Index (database)A separate, sorted list with the values of one or more columns of a table and where each row is. With it, the database finds a few rows without reading the whole table. In exchange, it takes up disk space and every write has to update it.Go to definition keeps each date with its id separately, sorted, along with the location of its row in the table.
You already had indexes: every Primary keyThe column, or group of columns, that identifies each row of a table. Its value can’t repeat or be missing, like an order number.Go to definition and every UNIQUE column comes with one, which PostgreSQL creates on its own to check right away whether a value already exists. The one for orders is called orders_pkey, and that’s why WHERE id = 50000 was already fast.
Inside, a B-tree
Section titled “Inside, a B-tree”The index is a B-treeThe way a database stores almost all its indexes. The entries sit in order at the bottom, in the leaves, and above them a few blocks say which leaf to look in. Each level multiplies what fits by hundreds, so any value is three or four steps away, even with millions of rows.Go to definition, stored in 8 kB pages:
- The leaves, at the bottom, have the entries in order, hundreds per page, and each one knows which is the next.
- The branches, above, say which leaf to look at for each range of dates.
- The root, at the top, says which branch to look at.
This is orders_by_date with 100,025 orders, and the path to one of them:
- Root1 page: which branch to look at
picks the branch
- Branch1 of 2 pages: which leaf to look at
picks the leaf
- Leaf1 of 384 pages, with about 260 dates in order
the row’s location
- The row, in a page of the orders table
Three pages of the index and one of the table, instead of the 736 of the whole table. And in the leaf, the next orders are right beside it, already in order.
Each level multiplies what fits by hundreds: if the table grew a hundred times, the path would still be three or four pages. And the tree is balanced: all the leaves are the same distance from the root.
EXPLAIN: the plan, before running
Section titled “EXPLAIN: the plan, before running”To find out which path PostgreSQL takes, put EXPLAIN in front of the query. This is the first page of the orders list, without an index:
EXPLAIN SELECT * FROM orders ORDER BY created_at DESC, id DESC LIMIT 10; QUERY PLAN--------------------------------------------------------------------------- Limit (cost=3897.75..3897.78 rows=10 width=27) -> Sort (cost=3897.75..4147.82 rows=100025 width=27) Sort Key: created_at DESC, id DESC -> Seq Scan on orders (cost=0.00..1736.25 rows=100025 width=27)(4 rows)It’s the Query planThe steps the database chooses to answer a query, such as reading the whole table or going through an index, sorting or joining tables. In PostgreSQL you see it with EXPLAIN and, running the query for real, with EXPLAIN ANALYZE.Go to definition: the steps PostgreSQL has chosen, without running anything. Each line with cost is a step, and it’s read from the bottom up: each one passes its rows to the one above.
Seq Scan on orders(sequential scan): reading the whole table, row by row.Sortsorts by the columns inSort Key, andLimitkeeps the first ten.rows=100025: how many rows it thinks will go through the step.width=27: how many bytes each one takes up.cost=0.00..1736.25: what it estimates it will cost, up to the first row and up to the last. They aren’t milliseconds, but a unit of its own for comparing plans.
PostgreSQL works out several plans and picks the cheapest, based on the table’s statistics: how many rows it has and what its values are like.
EXPLAIN ANALYZE: the plan, run
Section titled “EXPLAIN ANALYZE: the plan, run”With EXPLAIN ANALYZE in front of the same query, PostgreSQL really runs it and notes down what happened in each step:
QUERY PLAN----------------------------------------------------------------------------------------------------------------------------- Limit (cost=3897.75..3897.78 rows=10 width=27) (actual time=12.474..12.482 rows=10.00 loops=1) Buffers: shared hit=742 -> Sort (cost=3897.75..4147.82 rows=100025 width=27) (actual time=12.473..12.474 rows=10.00 loops=1) Sort Key: created_at DESC, id DESC Sort Method: top-N heapsort Memory: 26kB Buffers: shared hit=742 -> Seq Scan on orders (cost=0.00..1736.25 rows=100025 width=27) (actual time=0.003..4.158 rows=100025.00 loops=1) Buffers: shared hit=736 Planning: Buffers: shared hit=89 Planning Time: 0.197 ms Execution Time: 12.504 ms(12 rows)actual time=0.003..4.158: real milliseconds, up to the first row and up to the last.rows=100025.00: the real rows. If they look little like the estimated ones, the statistics are often out of date:ANALYZE ordersbrings them up to date.loops=1: the times the step was done.top-N heapsort: it keeps the first ten while it reads, without sorting the 100,000. But it reads them all.Buffers: shared hit=736: 8 kB pages read;hit, the ones that were already in memory, andread, the ones brought from disk. 736 are the whole table. PostgreSQL 18 shows it without being asked.Planning TimeandExecution Time: how long it took to plan and to run.
EXPLAIN ANALYZE runs the query: with a DELETE, it deletes. To see the plan of something that changes data, plain EXPLAIN.
With the index: four pages instead of 742
Section titled “With the index: four pages instead of 742”The same query, with orders_by_date created:
QUERY PLAN------------------------------------------------------------------------------------------------------------------------------------------ Limit (cost=0.42..0.89 rows=10 width=27) (actual time=0.039..0.042 rows=10.00 loops=1) Buffers: shared hit=1 read=3 -> Index Scan using orders_by_date on orders (cost=0.42..4756.48 rows=100025 width=27) (actual time=0.037..0.038 rows=10.00 loops=1) Index Searches: 1 Buffers: shared hit=1 read=3 Planning: Buffers: shared hit=108 read=1 Planning Time: 0.406 ms Execution Time: 0.058 ms(9 rows)Index Scan using orders_by_date: it goes down the tree to the newest order and carries on along the leaves. There’s noSort: the index is already in order.rows=10.00: it reads ten entries and stops.Index Searches: 1: it went down the tree once.Buffers: shared hit=1 read=3: four pages, three of the index and one of the table.
| Without an index | With an index | |
|---|---|---|
| Steps | Seq Scan, Sort and Limit |
Index Scan and Limit |
| Rows read | 100,025 | 10 |
Pages (Buffers) |
742 | 4 |
| Time | Over ten milliseconds | Hundredths of a millisecond |
Hundreds of times less time. And without an index the work grows with the table; with one, it hardly changes.
Multicolumn indexes: the order matters
Section titled “Multicolumn indexes: the order matters”A phone book is sorted by last name and, after that, by first name. You quickly find “García, Ana” and all the Garcías. But the Anas are spread all over the book.
A composite index, of several columns, works the same way: one on (a, b) is good for searching or sorting by a, or by a and b; not by b alone. That’s why the shop’s is on (created_at DESC, id DESC), the order of the list’s ORDER BY.
To choose the order: in front, the columns you compare with =; behind, the one you sort by or search by ranges. For “the pending ones, from newest to oldest,” (status, created_at): it goes straight to the pending ones, which are already by date.
What an index costs
Section titled “What an index costs”- Every write. Every
INSERTadds an entry to each index of the table, and so does anUPDATEthat changes a column of the index. With five indexes, an order is written in six places. - Disk. In
psql,\di+ orders*lists the indexes whose names start withorders, with their size, and\dt+ orders, the table:
List of indexes Schema | Name | Type | Owner | Table | Persistence | Access method | Size | Description--------+----------------+-------+-------+--------+-------------+---------------+---------+------------- public | orders_by_date | index | shop | orders | permanent | btree | 3104 kB | public | orders_pkey | index | shop | orders | permanent | btree | 2208 kB |(2 rows)
List of tables Schema | Name | Type | Owner | Persistence | Access method | Size | Description--------+--------+-------+-------+-------------+---------------+---------+------------- public | orders | table | shop | permanent | heap | 5928 kB |(1 row)The new index (btree, the B-tree) takes up 3 MB, more than half the table. That’s why you don’t put an index on every column, but one for each query that needs it, checking with EXPLAIN ANALYZE that it uses it.
Cursor pagination, now in SQL
Section titled “Cursor pagination, now in SQL”In lesson 3 of Phase 4, the Cursor (in pagination)A piece of text that marks how far you’ve read in a list split into pages, so you can ask for “the ones after this one.” The server writes it, and the client only sends it back as it is. Unlike “skip the first 20,” it doesn’t get it wrong if the list changes between one page and the next.Go to definition carried the id of the last order, and the primary key’s index was enough. But “newest first” goes by date, and the id only says in which order the rows came in: the 100,000 generated orders are older than the sample ones, with higher ids. So the cursor carries the value of the sort order and, to break ties, the id:
// (created_at, id) < ($1, $2) compares the two columns at once, the way words are sorted in a// dictionary: first the date and, if it's the same, the id. They're the orders that come after the// cursor. The index from migration 003 has this same order: PostgreSQL goes straight to the cursor// and reads only the page's orders, whether there are 25 orders or a million.export const ORDERS_BY_CURSOR = ` SELECT ${ORDER} FROM orders WHERE (created_at, id) < ($1, $2) AND ($3::text IS NULL OR status = $3) ORDER BY created_at DESC, id DESC LIMIT $4`;${ORDER}: the order’s columns, as indata.ts.(created_at, id) < ($1, $2)compares the two pairs the way a dictionary sorts words: first the date and, if it’s the same, the id. They’re the orders behind the cursor.$1and$2are parameters, as in lesson 5, “Node and PostgreSQL”.$3::text IS NULL OR status = $3: the optional filter by status. Without a status,$3isNULLand the condition is always met.::texttells PostgreSQL that$3is text: withIS NULLalone, it wouldn’t know.ORDER BY created_at DESC, id DESC: the index’s order. PostgreSQL goes down to the cursor and reads only the page.LIMIT $4: one more than fits; if it arrives, there’s another page.
It’s keyset pagination. Since the cursor is opaque, no client changes its code. But a cursor saved from before, which only carries the id, now gets a 422, in /v1 too. According to Phase 4, that breaks, although only for whoever was halfway through the list when you deployed: they have to go back to the first page. So as not to break even that, the server would accept both formats for a while.
Page 9001, with an offset and with the cursor of order 90000:
EXPLAIN ANALYZE SELECT * FROM ordersORDER BY created_at DESC, id DESC LIMIT 10 OFFSET 90000; QUERY PLAN---------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=4279.80..4280.28 rows=10 width=27) (actual time=14.108..14.117 rows=10.00 loops=1) Buffers: shared hit=665 read=344 -> Index Scan using orders_by_date on orders (cost=0.42..4756.48 rows=100025 width=27) (actual time=0.008..10.974 rows=90010.00 loops=1) Index Searches: 1 Buffers: shared hit=665 read=344 Planning: Buffers: shared hit=109 Planning Time: 0.274 ms Execution Time: 14.135 ms(9 rows)EXPLAIN ANALYZE SELECT * FROM ordersWHERE (created_at, id) < ('2026-07-30 21:25:00+00', 90000)ORDER BY created_at DESC, id DESC LIMIT 10; QUERY PLAN---------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=0.42..2.10 rows=10 width=27) (actual time=0.038..0.042 rows=10.00 loops=1) Buffers: shared hit=3 read=1 -> Index Scan using orders_by_date on orders (cost=0.42..1659.79 rows=9864 width=27) (actual time=0.037..0.037 rows=10.00 loops=1) Index Cond: (ROW(created_at, id) < ROW('2026-07-30 21:25:00+00'::timestamp with time zone, 90000)) Index Searches: 1 Buffers: shared hit=3 read=1 Planning: Buffers: shared hit=108 Planning Time: 0.249 ms Execution Time: 0.063 ms(10 rows)Both use the index and give the same orders, from 90001 to 90010. But look at rows:
- With
OFFSET, 90,010. PostgreSQL can’t skip rows without counting them: it reads 90,000 entries and throws them away. Over a thousand pages. - With the cursor, 10.
Index Condsays that the tree itself resolves the condition: it goes straight down to order 90000. Four pages.
The offset takes longer the further away the page is; the cursor, the same on the first page as on the last.
In production: CREATE INDEX CONCURRENTLY
Section titled “In production: CREATE INDEX CONCURRENTLY”While CREATE INDEX builds the index, the table can be read but not written. With 100,000 rows it’s less than a second; with a hundred million, it can be minutes without being able to save an order.
CREATE INDEX CONCURRENTLY builds it without blocking writes. It takes longer, if it fails it leaves an invalid index that you have to drop, and it can’t go inside a TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition:
shop=> BEGIN;BEGINshop=*> CREATE INDEX CONCURRENTLY orders_quantity ON orders (quantity);ERROR: CREATE INDEX CONCURRENTLY cannot run inside a transaction blockshop=!> ROLLBACK;ROLLBACKYou’ll see the prompt’s * and ! in lesson 8, “Transactions”. Your migration runner puts each one in a transaction, so it would have to learn that exception. In the shop it isn’t needed; in production, it’s the norm.
Try it
Section titled “Try it”The goal: time the orders list without an index and with one, in the browser and in your database, leave the API paginating in SQL and pit the offset against the cursor.
Before and after, in the browser
Section titled “Before and after, in the browser”This playground generates 50,000 orders, times the first page, creates the index and times it again. Press “Run”:
playground · PostgreSQL in your browser
A real PostgreSQL, with the shop’s data. What you change stays on this page.
What’s new is in the INSERT:
INSERT INTO orders (…) SELECT …: the rows don’t come from aVALUES, but from aSELECT, one for each row it returns.generate_series(1, 50000) AS n: a function that returns the numbers from 1 to 50,000, in a columnn.n % 3 + 1:%is the remainder of dividing by 3 (0, 1 or 2); with+ 1, products 1 to 3, in turns.timestamptz '…' - n * interval '1 minute': each order, one minute before the previous one.ANALYZE orders: brings the statistics up to date.
Look at the two plans: Seq Scan and Sort before, Index Scan after. It’s PostgreSQL 18.3 in the browser: the times change, not the shape of the plan.
Now press “Reset data”, put ORDER BY quantity DESC in both queries and run: both plans come out with Seq Scan, because the index doesn’t have quantity. Without resetting, the CREATE INDEX would fail: the index already exists.
In your database: a hundred thousand orders
Section titled “In your database: a hundred thousand orders”You’re still in ~/backend-course/phase-3/shop-api, with the code from lesson 6. Download this lesson’s folder: from ~/backend-course/phase-3, curl -O https://backenddesdecero.com/practicas/shop-api/21-indexes.tar.gz and tar -xzf 21-indexes.tar.gz.
Copy the script that generates the orders, cp ../21-indexes/scripts/many-orders.ts scripts/, and add to "scripts" in package.json the line "db:many-orders": "node --env-file-if-exists=.env scripts/many-orders.ts". It’s the playground’s INSERT, with 100,000, all inside PostgreSQL:
// generate_series(1, 100000) gives the numbers from 1 to 100,000, one per row, and the INSERT// creates an order with each one: it all happens inside the database, in a single query. One per// minute, going back from the first sample order.await pool.query(` INSERT INTO orders (product_id, quantity, status, created_at) SELECT n % 3 + 1, n % 4 + 1, 'shipped', timestamptz '2026-10-01 09:00:00+00' - n * interval '1 minute' FROM generate_series(1, 100000) AS n`);// ANALYZE updates the table's statistics (how many rows it has, what its values are like):// PostgreSQL uses them to decide how to run each query.await pool.query('ANALYZE orders');1. A hundred thousand orders
npm run db:many-ordersWhat you will see:
> shop-api@1.0.0 db:many-orders> node --env-file-if-exists=.env scripts/many-orders.ts
There are now 100025 ordersThe 100,000 new ones and the 25 sample ones; if you created others with the API, you’ll get more. If you get relation "orders" does not exist, you’re missing npm run db:migrate.
Open psql -d shop and time the first page:
2. Without an index
EXPLAIN ANALYZE SELECT * FROM orders ORDER BY created_at DESC, id DESC LIMIT 10;You get the plan from “EXPLAIN ANALYZE: the plan, run”, with your times: Seq Scan with rows=100025.00, Sort and about 740 pages in Buffers. If you see Index Scan, you already have the index: check whether db/migrations/ has the 003.
Copy the migration, cp ../21-indexes/db/migrations/003-orders-index.sql db/migrations/, and apply it:
3. The index migration
npm run db:migrateWhat you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 003-orders-index.sqlOnly the 003: the others are already in the migrations table.
4. With an index
EXPLAIN ANALYZE SELECT * FROM orders ORDER BY created_at DESC, id DESC LIMIT 10;You get the plan from “With the index: four pages instead of 742”: Index Scan, ten rows and four pages. If you run it again, read=3 becomes hit=4: the pages are already in memory.
The API, paginating in SQL
Section titled “The API, paginating in SQL”Now the code. Copy it from the folder or write the changes yourself:
src/pagination.ts: the cursor carries the date and the id, andpageByCursorandpageByOffsetquery PostgreSQL instead of cutting a list.src/data.ts: it exportsORDER,OrderRowandtoOrder, and deletesordersNewestFirst. When an order is created,date_trunc('milliseconds', now())saves the time with milliseconds, as the API gives it, so that the cursor points to exactly that order.src/schemas.ts: the cursor’s schema checks the date and the id.src/v2.ts: the orders route calls both functions withawait.
Copy the tests, cp ../21-indexes/test/*.test.ts test/, and run the new one:
5. The index tests
npm test -- test/indexes.test.tsWhat you will see:
> shop-api@1.0.0 test> node --env-file=test/.env --test --test-concurrency=1 test/indexes.test.ts
✔ migration 003 creates the index for the orders list: by date and by id, highest first (63.628085ms)✔ by cursor every order is seen exactly once, even if new ones arrive between two pages (43.795553ms)✔ an old cursor, which only carried the id, is no longer valid: 422 (1.990177ms)✔ with 100,000 orders, the list uses the index; without it, it reads the whole table (633.318292ms)ℹ tests 4ℹ suites 0ℹ pass 4ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 1046.430073The last one does the same as you, in shop_test. If the first one fails, the 003 is missing from db/migrations/. Outputs from Node 26.11.1; your times will be different. Run the whole npm test too.
Start the server with npm run dev and, in another terminal, ask for a page of two:
6. The new cursor
curl -i 'localhost:3000/v2/orders?limit=2'What you will see:
HTTP/1.1 200 OKcontent-type: application/jsonlink: <http://localhost:3000/v2/orders?limit=2&cursor=WyIyMDI2LTEwLTA4VDAyOjAwOjAwLjAwMFoiLDI0XQ>; rel="next"vary: Originx-request-id: 6c87f496-ffac-4e81-bde7-57fae8c7bdedcontent-length: 191Date: Tue, 13 Oct 2026 23:47:54 GMTConnection: keep-aliveKeep-Alive: timeout=5
[{"id":25,"productId":2,"quantity":2,"status":"pending","createdAt":"2026-10-08T09:00:00.000Z"},{"id":24,"productId":1,"quantity":1,"status":"pending","createdAt":"2026-10-08T02:00:00.000Z"}]The cursor in link is longer. node -p "Buffer.from('WyIyMDI2LTEwLTA4VDAyOjAwOjAwLjAwMFoiLDI0XQ', 'base64url').toString()" decodes it: ["2026-10-08T02:00:00.000Z",24], the date and the id of order 24. Your x-request-id and your date will be different.
Offset versus cursor
Section titled “Offset versus cursor”With 50,000 orders and the index, page 4501 with OFFSET 45000 and with the cursor of order 45000:
playground · PostgreSQL in your browser
A real PostgreSQL, with the shop’s data. What you change stays on this page.
Look at rows in the Index Scan: 45,010 with the offset and 10 with the cursor. Press “Reset data”, change OFFSET 45000 to OFFSET 100 and run: 110.
In psql, with your 100,000, try the two from “Cursor pagination, now in SQL”: rows=90010.00 and rows=10.00.
When you’re done, remove the generated orders, the ones before the first sample one:
7. Back to 25 orders
DELETE FROM orders WHERE created_at < '2026-10-01 09:00:00+00';What you will see:
DELETE 100000The index stays. If you get another number, you ran the script more than once.
You have already seen it
Section titled “You have already seen it”- Your phone’s contacts, sorted by name: you go straight to the letter.
- The table in Phase 4 said that the offset “reads and throws away” rows. Now you’ve measured it.
Common mistakes
Section titled “Common mistakes”- An index on every column, just in case. They slow down writes and take up disk space. Add the ones a query needs.
- A composite index in the wrong order.
(created_at, status)is no good for searching bystatus: the first column rules. EXPLAIN ANALYZEwith anUPDATEor aDELETE. It really runs it. Use plainEXPLAIN.- Measuring with a small table. With 25 rows, PostgreSQL reads the table even if there’s an index, and it’s right to: it’s one page.
CREATE INDEXon a big table in production. It blocks writes:CONCURRENTLY.
Summary
Section titled “Summary”- An index is a sorted copy of some columns, with the location of each row. It’s a B-tree: any value is a few pages away, even with millions of rows.
EXPLAINshows the plan;EXPLAIN ANALYZEruns it and notes down rows, times and pages. It’s read from the bottom up:Seq Scanreads the whole table,Index Scangoes through the index.- In a composite index, the first column rules.
- Every index is paid for on every write and in disk space: one for each query that needs it.
- With an index in the same order, the cursor
(created_at, id) < ($1, $2)reads only the page;OFFSETreads and throws away everything it skips.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Indexes (PostgreSQL documentation): the types, composite ones and when they’re used.
- Using EXPLAIN (PostgreSQL documentation): every line of a plan.
- Use The Index, Luke (Markus Winand): a free book about indexes.
- No offset (Markus Winand): why keyset pagination wins.