Skip to content
Reviewed by Siddharth Sharma Nov 16, 2026

Home › Guides › Database indexing

Tech Explained · 2026

How Database Indexing Works in 2026: B-Tree Internals, EXPLAIN Output and a 5 Million Row Worked Example

Database indexing works by storing a sorted copy of one or more columns in a B-tree, so the engine finds rows in a handful of page reads instead of scanning the whole table. On a 5 million row table measured for this guide, one index cut the same query from 93.95 ms to 0.17 ms.

16 November 20269 min readBy the 360 Digital Transformation Editorial Team
Key takeaways
  • An index is a sorted side table, not a setting. It holds the indexed columns plus a pointer to the row, and it is maintained on every write.
  • 22 page reads beat 46,234. That is the measured difference the index made to one filter on five million rows.
  • EXPLAIN is where slow queries confess. A large Rows Removed by Filter count means the condition never reached the index.
  • A function around the column kills it. lower(city) = 'pune' took 362.95 ms where city = 'Pune' took 26.48 ms, on the same index.
  • Column order is the whole design. Querying the second column of a composite index alone cost 105.18 ms against 17.44 ms for a leading-column match.
  • You pay in writes. Four indexes made a 200,000 row insert roughly four times slower in the same test.

Picture a two person data team at a mid size Indian insurer. The claims dashboard that refreshed in two seconds now takes forty, and nobody deployed anything. The table just got bigger. What stands between a 90 ms query and a 90 second one is whether the database can find your rows without reading all of them.

Every number below was measured live on PostgreSQL 16.15, the build released on 13 August 2026 according to the official release notes, against a 5,000,000 row table. These are readings, not illustrations, and you can reproduce them in about ten minutes.

How Database Indexing Works: Three Hops Instead of a Whole Table

A table on disk is a pile of 8 KB pages, and rows sit wherever there was room when they were written. There is no order. So when you ask for customer_id = 84217, the only honest thing the engine can do is read every page and check every row: 46,234 pages on our table.

An index changes the question. It holds just the indexed column values, kept sorted, each paired with a pointer to where the full row lives, which Postgres calls a ctid. Because it is sorted, the engine does what you do with a phone book: start in the middle, go left or right, repeat. The structure is a B-tree, and the property that matters is fan out. Each 8 KB index page holds hundreds of keys, so five million rows sit in a tree roughly three levels deep, which is why the lookup below costs three page reads and not thirty.

The path a B-tree lookup actually takes

Three index page reads narrow 5,000,000 rows to one leaf entry, then a row pointer returns the row.

How a B-tree index finds one row A query for customer_id 84217 reads the root index page, then one internal page, then one leaf page, and finally follows a row pointer into the table heap, instead of scanning 46,234 table pages. Root index page keys 1 to 200,000 1 to 66,000 66,001 to 133,000 133,001 to 200,000 83,900 to 84,100 leaf: 84,101 to 84,300 84217 points to a ctid Table heap: 46,234 pages, 361 MB. Only 19 pages are read. hop 1: pick a range hop 2: pick a leaf hop 3: follow the pointer

Structure per the PostgreSQL B-tree access method; page counts and sizes measured on the test table, 16 November 2026.

Two consequences fall out of that picture, and the rest of this guide is about them. An index helps only when it can rule out most of the tree, which is why a customer ID is a good candidate and a four-value status column is not. And it is a second copy of your data, so every write maintains it.

A plain CREATE INDEX gives you a B-tree, good for equality, ranges, sorting and prefix matching with LIKE 'pun%'. The specialised types handle shapes a sorted tree cannot: GIN for full text and jsonb, GiST for geometry, BRIN for huge append only tables whose column tracks physical order, which is the partitioning instinct the DP-700 syllabus drills in a live Microsoft Fabric data engineering programme. A vector index is the same idea with a different distance function, which is how a RAG or AI agent build searches millions of embeddings in under a second. Indexing is not a database feature. It is the strategy of not looking at everything.

The Worked Example: 5 Million Rows, One Index, 93.95 ms to 0.17 ms

Create the table, load five million rows, measure, index, measure again.

CREATE TABLE orders (
  order_id    bigserial PRIMARY KEY,
  customer_id int           NOT NULL,
  city        text          NOT NULL,
  status      text          NOT NULL,
  amount      numeric(10,2) NOT NULL,
  placed_at   timestamptz   NOT NULL
);

INSERT INTO orders (customer_id, city, status, amount, placed_at)
SELECT (random()*200000)::int + 1,
       (ARRAY['Bengaluru','Pune','Chennai','Hyderabad',
              'Mumbai','Kochi','Jaipur','Indore'])[1+floor(random()*8)],
       (ARRAY['placed','shipped','delivered','cancelled'])[1+floor(random()*4)],
       round((random()*4900 + 100)::numeric, 2),
       now() - (random()*540)::int * interval '1 day'
FROM generate_series(1,5000000);

VACUUM ANALYZE orders;

Do not skip that last line. The planner decides whether to use an index from table statistics, and stale statistics are behind a surprising share of "my index does nothing" complaints. The load lands a 361 MB heap. Now make the database show its work:

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT order_id, amount, placed_at FROM orders WHERE customer_id = 84217;

 Gather (actual time=15.893..93.904 rows=19 loops=1)
   Buffers: shared hit=12682 read=33552
   ->  Parallel Seq Scan on orders (actual time=6.448..89.507 rows=6 loops=3)
         Filter: (customer_id = 84217)
         Rows Removed by Filter: 1666660
 Execution Time: 93.950 ms

Read the Rows Removed by Filter line again. To return 19 rows, the database discarded 1,666,660 per worker and touched 46,234 pages. Now give it a choice:

CREATE INDEX idx_orders_customer ON orders (customer_id);
VACUUM ANALYZE orders;

 Bitmap Heap Scan on orders (actual time=0.040..0.134 rows=19 loops=1)
   Heap Blocks: exact=19
   Buffers: shared hit=3 read=19
   ->  Bitmap Index Scan on idx_orders_customer (actual time=0.027..0.027 rows=19)
         Index Cond: (customer_id = 84217)
 Execution Time: 0.172 ms

Three index pages, nineteen heap pages, 0.172 ms. The index cost 37 MB against a 361 MB table and took 1.72 seconds to build. That is the deal: roughly ten percent more storage and a slower write path, for a query that stops caring how big the table gets. Reading plans like this against a loaded table, not a ten row toy, is the SQL module of 360DT's live data analyst programme.

Query Plan the planner chose 8 KB pages read Execution time
WHERE customer_id = 84217, no index Parallel Seq Scan 46,234 93.95 ms
Same query, B-tree on customer_id Bitmap Index Scan plus Bitmap Heap Scan 22 0.17 ms
customer_id BETWEEN 5000 AND 5200, returning amount Bitmap Heap Scan, 4,770 heap blocks 4,778 220.46 ms
Same query, index with INCLUDE (amount) Index Only Scan, Heap Fetches: 0 424 0.94 ms

Same table, six query shapes, measured

Index design, not hardware, spans the whole range below. Bars are proportional to execution time.

lower(city) = 'pune'function blocks the index
362.95 ms1.46M rows filtered
status onlysecond column of a composite
105.18 mswhole index read
customer_id = 84217no index at all
93.95 ms46,234 pages
city = 'Pune'same index, no function
26.48 msindex condition
city and statusleading column present
17.44 msindex only scan
customer_id = 84217with the B-tree
0.17 ms22 pages

All six measured in one PostgreSQL 16.15 session on the same 5,000,000 row table, 16 November 2026.

Reproduce it on a free tier
  • Use one million rows, not five. Our table plus indexes reached roughly 690 MB. At 1,000,000 rows it measures 73 MB.
  • Neon's free plan lists 1 GB of storage per project and 100 CU-hours across up to 100 projects, per its pricing page checked today. Supabase's free plan lists a 500 MB database and pauses a project after a week of inactivity.
  • Local is easier still. A Postgres container needs no account, and every command here runs unchanged.

How to Read EXPLAIN Output Without Guessing

Most people add an index, see no improvement, and conclude indexing is voodoo. Usually the plan said exactly what happened and nobody read it.

What you see What it means What to do
Seq Scan Every page of the table was read Fine on small tables or when you want most rows. On a big table with a narrow filter, an index is missing
Index Scan Walked the tree, fetched matching rows What you want for a few rows, especially with ORDER BY ... LIMIT
Bitmap Index Scan then Bitmap Heap Scan Collected row locations, then read heap pages in physical order Normal for dozens to thousands of matches. Watch Heap Blocks
Index Only Scan, Heap Fetches: 0 The index had every column needed The fastest outcome available. See covering indexes below
Rows Removed by Filter Rows were read, then thrown away A big number is the smoking gun: the condition could not reach the index
Buffers: shared hit / read Pages from cache versus from disk The honest cost measure. Compare these, not milliseconds

That last row is the habit worth building. The second run of any query is faster because the data is cached, which makes before and after timings flattering and sometimes meaningless. Page counts do not move with cache state.

Also read: SQL Query Optimization in 2026: 10 Mistakes That Make Queries Slow picks up here with the rewrite for each bad plan.

Composite Index Column Order: Why (city, status) Is Not (status, city)

This is where real index design goes wrong. Build one index on two columns:

CREATE INDEX idx_orders_city_status ON orders (city, status);

Filter on both columns and you get a clean index only scan at 17.44 ms. Filter on only the second one, WHERE status = 'shipped', and the same index gets used but has to be read end to end: 105.18 ms. Six times slower, one column dropped from the predicate.

A B-tree is sorted by the first column, then within that by the second, so skipping the leading column is like looking up a surname in a directory sorted by city. Order the columns by what your queries filter: the one present in every query first, the one that narrows most next, the one you only sort by last.

One update to that advice. PostgreSQL 18, released 25 September 2025 per the official release notes, added skip scan for multicolumn B-trees. The documentation is blunt about the limits: the planner tends to use it only when the leading column has few distinct values, and with many distinct values a sequential scan usually wins instead. Treat it as a safety net for the query you forgot, not permission to stop thinking about column order.

Covering Index: One INCLUDE Clause, 220 ms to 0.94 ms

Back to the insurer's dashboard, which pulls a range of customers and an amount. With the plain index, the plan finds rows fast then spends all its time fetching them: 8 index pages to locate 5,043 rows, then 4,770 scattered heap pages to read them. Total 220.46 ms. Put the extra column in the index and the table is never visited.

CREATE INDEX idx_orders_cust_incl ON orders (customer_id) INCLUDE (amount);

 Index Only Scan using idx_orders_cust_incl (actual time=0.070..0.725 rows=5043)
   Heap Fetches: 0
   Buffers: shared hit=402 read=22
 Execution Time: 0.938 ms

That is 235 times faster on the same data. The official PostgreSQL documentation notes index only scans are supported by the B-tree, GiST and SP-GiST methods, and INCLUDE carries payload columns that are not part of the search key.

Now the part tutorials leave out. That covering index measured 150 MB against 37 MB for the plain one, because every entry carries the amount too. Four times the storage for one dashboard query, on a table whose indexes already totalled 328 MB against a 361 MB heap. Do it on purpose, for a query that runs constantly, not as a reflex.

When Not to Use an Index: 6 Cases Where It Costs You

Most indexing problems in a real job are not missing indexes. They are indexes that exist, do nothing, and are paid for on every write.

Six indexes that lose money

Each case below was either measured in this session or is visible in the plans above.

1

A function wraps the column

362.95 ms with lower(city) = 'pune', 26.48 ms with city = 'Pune', same index. The index stores city values, not lowercased ones. Fix it by indexing the expression itself: CREATE INDEX ON orders (lower(city)).

14x slower
2

The column has four distinct values

Any filter on status matches a quarter of five million rows, so an index cannot rule out enough to beat a scan. The escape hatch is a partial index on just the rare value: WHERE status = 'cancelled'.

Low selectivity
3

The table is write heavy

200,000 inserts took 429 to 455 ms into a bare table, and 1,694 to 1,985 ms into an identical one with four indexes, which also carried 18 MB of index on a 29 MB table.

4x write cost
4

The pattern starts with a wildcard

LIKE 'pun%' can use a B-tree because the prefix is known. LIKE '%pune' cannot, for the same reason you cannot find a name in a directory knowing only its last letters. Infix search needs a trigram index.

Unusable prefix
5

Nobody queries it

In this very session orders_pkey sat at 107 MB with zero scans, because nothing ever looked an order up by its ID. Real storage, real write cost, no benefit. The primary key stays. The four indexes somebody added in 2023 probably should not.

Dead weight
6

The query wants most of the table

A monthly aggregate over 80 percent of rows is not an indexing problem. Row by row lookups are the wrong shape, and a columnar store beats any index you build. Telling the two problems apart is most of the skill.

Wrong tool

Timings from the same PostgreSQL 16.15 session, 16 November 2026.

The honest caveat, because indexing gets oversold as the cure for slow databases: an index speeds up finding rows. It does nothing for a query that returns half the table, a bad join order, a model that needs six joins to answer one question, or an analytics workload that should never have been pointed at a transactional database. If a dashboard scans 400 million rows per refresh, the fix is upstream of indexing.

The audit is three lines, and worth running on any database you inherit:

SELECT relname AS table, indexrelname AS index, idx_scan AS scans,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY idx_scan ASC, pg_relation_size(indexrelid) DESC;

Anything at the top with zero scans and real size is a candidate, provided the counters have been running long enough to cover quarterly reports as well as daily ones.

Also read: the SQL Commands Cheat Sheet 2026 for the execution order that explains why some predicates can never reach an index.

Live course

Learn SQL the way production databases behave, not the way tutorials describe them

Live online·Sat–Sun, 8–11 PM IST·70+ hrs·Rs 24,999

Ten weeks of live weekend classes covering Python, SQL, advanced Excel and Power BI, with preparation for the Microsoft PL-300 certification. Includes hands on projects, mentor support and placement guidance.

Explore the course
Data Analyst Course: Excel, SQL, Python & Power BI (PL-300)

How to Add an Index to a Live Table Without Taking the Site Down

Everything above ran on a database nobody else was using. On production, a plain CREATE INDEX holds a lock that blocks writes for the whole build. Ours took 1.72 seconds, which sounds survivable until the table is 500 million rows and every insert queues behind it for twenty minutes.

CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);
-- measured 2,935 ms versus 1,720 ms plain: slower build, writes keep flowing

What usually goes wrong here is worth hearing before 11 PM on a deploy night. The concurrent build cannot run inside a transaction, and most migration tools wrap everything in one, so you get this exact message:

ERROR:  CREATE INDEX CONCURRENTLY cannot run inside a transaction block

The second trap is quieter. If a concurrent build fails partway, the official documentation states the command fails but leaves behind an invalid index, and the fix is to drop it and build again. An invalid index is still maintained on writes but never used for reads, so you pay and get nothing. After any failed migration, check:

SELECT indexrelid::regclass AS index FROM pg_index WHERE NOT indisvalid;
Before you run it on production
  • Mark the migration non-transactional. In Rails, Django or Flyway this is a per migration flag, and forgetting it is the most common cause of a failed index deploy.
  • Verify in the deploy, not the next morning. Run the indisvalid check as its last step.
  • Consider a lower fill factor on hot tables. The official CREATE INDEX documentation notes values in the 50 to 90 range can help B-tree indexes on heavily inserted or updated tables, at the cost of a larger index.
  • Confirm the plan changed. Re-run EXPLAIN (ANALYZE, BUFFERS) on the real query. An index no plan uses is a liability. And keep the server supported: per the official release notes, fixes for the PostgreSQL 14 series end in November 2026.

On managed infrastructure, parameter groups, maintenance windows and replica lag all shape when an index can safely be built, which is the operational judgement the database module of an AWS Solutions Architect and DevOps programme is built around, and what the AZ-305 architecture track covers on Azure. The certifications overview maps exams to roles.

Also read: What Is a Data Warehouse? for how analytical engines handle the "most of the table" case with partitioning and column pruning instead.

How to Learn Database Indexing Properly

If I were starting this weekend I would not read more about indexes. I would load a few million rows and break things on purpose: wrap a column in a function, order the composite columns wrongly, add four indexes and time an insert. Understanding comes from reading plans you caused, and everything in this guide was produced that way in one sitting.

What a live programme adds is the part that is hard to self assess: whether your reasoning about a plan is right, and what an interviewer is listening for when they ask why an index was ignored. 360DT's data analyst course teaches SQL alongside Python, Excel and Power BI with PL-300 preparation, on weekends, so it sits next to a job. Before paying for anything, a free webinar or a demo class is the cheaper way to test the teaching.

Frequently asked questions

Do I need to understand how database indexing works to pass a SQL interview?

Above entry level, yes. The question is rarely "what is an index" and usually "here is a slow query, what would you check". The expected answer walks the plan: which filter is selective, whether the predicate can reach the index, what the column order should be. Saying you would check rows removed by filter first puts you ahead of most candidates.

Does adding an index make a database faster or slower?

Both, which is the point. Matching reads get dramatically faster, as in the 93.95 ms to 0.17 ms above. Writes get slower, because every insert, update and delete maintains the index: four of them made a 200,000 row insert about four times slower in the same test.

Why is my query still slow after adding an index?

Four suspects, in order of frequency. A function or cast wraps the column. The filter is not selective enough, so the planner chose a scan on purpose. The query omits the leading column of a composite index. Or statistics are stale because ANALYZE has not run since the data changed.

What is the difference between a clustered and a non-clustered index?

A clustered index stores the rows themselves in index order, so there is only one per table. MySQL's InnoDB engine works this way on the primary key, and SQL Server offers it as a choice. PostgreSQL has none: the heap stays unordered and every index points into it, which is why Heap Fetches matters so much in the plans above.

What is a covering index in PostgreSQL?

An index holding every column a query needs, so the engine answers from the index and skips the table. You add payload columns with INCLUDE. Above, it turned a 220 ms query into a 0.94 ms one, and grew the index from 37 MB to 150 MB.

How do I find unused indexes in my database?

Query pg_stat_user_indexes sorted by idx_scan ascending, as above. Zero scans plus real size makes a drop candidate. One caution: those counters reset when statistics are reset, so let them run a full business cycle before deleting an index a quarter end report depends on.

About this guide. 360 Digital Transformation is an Anthropic Partner and a Microsoft Authorized Training Partner. Other certification bodies, vendors and employers named here are not affiliated with us. Tools and versions change quickly; commands and figures cited were checked on 16 November 2026.

Learn it live with 360 Digital Transformation

Turn this guide into a skill employers can see

Live weekend cohortEMI available

Data Analyst Course: Excel, SQL, Python & Power BI (PL-300)

Rs. 24,999

Tools and platforms you work with

  • Microsoft Excel
  • PostgreSQL
  • MySQL
  • Python
  • pandas
  • NumPy
  • matplotlib and seaborn
  • Jupyter
Add bonus modules
See the syllabus and batch dates

Other live courses on this career path