Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 121/ 160
07. Indexing, Query Optimization & Performance Tuning

How Databases Store Data on Disk (Pages, Blocks, Heap, B-Trees)

Understand pages, heaps, and B-Tree leaf structure behind query performance.

IntermediatePages / Blocks · Heap3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Data lives in small fixed-size boxes; the database always fetches whole boxes, and indexes are lists that say which box to open.

Think of it like…

A warehouse of identical shelves: goods are stored in boxes of a fixed size (pages), each item has a shelf-and-slot label (ctid), and a separate catalogue (the index) lists items in order with their labels. Fetching one item still means carrying a whole box down.

Where you’ve seen it

An orders table has rows of about 200 bytes, so roughly 40 fit in an 8 kB page: 10 million rows take about 250,000 pages, around 2 GB. Fetching one customer's 300 orders through an index costs about 300 heap page reads if the rows are scattered, but only around 8 if they were inserted together. That's the difference EXPLAIN (ANALYZE, BUFFERS) shows as shared hit and read counts.

Words you’ll hear

Page / block
The fixed-size unit of storage and I/O: 8 kB (PostgreSQL), 16 kB (InnoDB).
Heap
PostgreSQL's table storage: unordered pages of row versions.
ctid / TID
A row's physical address: (page number, item slot).
Clustered index
InnoDB's table layout: rows stored in primary-key order in a B-tree.

Visual diagram

Loading interactive diagram

Theory & example queries

Pages, heaps and row addresses

A PostgreSQL heap page has a small header, an array of line pointers growing from the front, row data growing from the back, and free space in between. Each row version carries a header of about 23 bytes with visibility information for MVCC. A row's ctid, which you can see with SELECT ctid, * FROM orders LIMIT 5, is its page number and slot. Values larger than about 2 kB are compressed or moved to a separate TOAST table, so wide text columns don't bloat every page.

Reads go through the buffer cache (shared_buffers, backed by the operating system's cache). A Seq Scan reads pages in order, which is efficient. An index lookup reads a few index pages, then one heap page per matching row, which is random I/O. How many distinct pages that touches depends on whether matching rows sit together, which is what the planner's correlation statistic estimates.

Looking at physical layoutQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  ctid,3  id4FROM5  orders6WHERE7  customer_id = 428LIMIT9  5;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/9
query.sql
1SELECT2  pg_relation_size('orders') / 8192 AS pages,3  pg_size_pretty(pg_relation_size('orders')) AS size;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative PostgreSQL layout results
ctid | id (4812,7) | 91240 (4812,8) | 91241 (5030,12) | 92703 pages | size 245 | 1960 kB

Note: Representative values only. ctid, page placement and relation size depend on PostgreSQL storage state, page size and the live data.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

and

Key takeaway: Rows live in 8 kB pages; index lookups cost a heap page per scattered row.

Updates, fill factor and clustered storage

PostgreSQL never updates a row in place: UPDATE writes a new version and marks the old one dead, to be cleaned up by VACUUM. If the new version fits on the same page and no indexed column changed, it's a HOT update that doesn't touch the indexes. Lowering a table's fillfactor (for example to 90) leaves room on each page for this, which helps tables with frequent updates.

InnoDB stores each table as a B-tree on the primary key, with full rows in the leaf pages. Primary-key lookups and ranges are fast because rows are physically in key order, and secondary indexes store the primary key, so a secondary lookup is two B-tree searches. Random primary keys (UUIDv4) insert into random pages and cause page splits; sequential keys (auto-increment or UUIDv7) append to the end.

Leaving room for HOT updatesQuery example
1Input dataStart from the source rows or state that the statement sees.
sessions
2 rows
sessions sample rows
iduser_idlast_seen_atactive
112026-11-21 09:00true
222026-11-20 18:30false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER TABLE sessions2SET3  (fillfactor = 85);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/3
query.sql
1SELECT2  n_tup_upd,3  n_tup_hot_upd4FROM5  pg_stat_user_tables6WHERE7  relname = 'sessions';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative status and counters
ALTER TABLE n_tup_upd | n_tup_hot_upd 4200 | 3570

Note: The fillfactor is used as pages are rebuilt or rows are inserted/updated. Statistics counters are cumulative, depend on workload and may be reset, so this HOT ratio is illustrative.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

then check

to see the share of updates that were HOT.

Key takeaway: PostgreSQL: new version per update, HOT if possible; InnoDB: rows in primary-key order.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Executor

A query needs a row

The plan decides to read the table sequentially or look the row up through an index.

Focus at this step

Index Scan using orders_customer_idx

What to watch at this step
Plan
chooses the path
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Databases store tables in fixed-size pages (8 kB in PostgreSQL and SQL Server, 16 kB in MySQL's InnoDB), and always read and write whole pages. In PostgreSQL a table is a heap: pages of rows in no particular order, each row addressed by a ctid (page number, slot). Indexes are separate B-trees whose leaf entries point to those addresses. InnoDB instead stores rows inside the primary-key B-tree itself, a clustered index.

Why it matters: Almost every performance rule follows from pages: why fetching 1,000 scattered rows can cost 1,000 page reads, why narrow rows scan faster, why random UUID primary keys hurt InnoDB inserts, and why an UPDATE leaves the old version behind. Interviews for backend and database roles ask how a row is found on disk, because it shows whether you understand what EXPLAIN is really measuring.

When to reach for it

  • Explaining why an index scan is slower than expected
  • Choosing primary keys for InnoDB tables
  • Tuning update-heavy tables with fillfactor

When to avoid or be careful

  • Assuming the database can read a single row without its page
  • Random UUIDv4 primary keys on large InnoDB tables
  • Very wide rows when most queries need a few columns

Heap tables vs clustered (index-organised) tables

Heap + separate indexes (PostgreSQL)
Best for: General workloads with several access paths

Strengths: All indexes are equal; inserts go anywhere with free space.

Watch out: Index lookups need an extra heap page read per row.

Clustered primary key (InnoDB, SQL Server clustered index)
Best for: Workloads dominated by primary-key lookups and ranges

Strengths: Rows stored in key order; PK ranges read few pages.

Watch out: Secondary lookups are two searches; random keys cause page splits.

Columnar storage (warehouses)
Best for: Analytics reading few columns of many rows

Strengths: Reads only needed columns; compresses well.

Watch out: Slow for single-row lookups and updates.

Interview signals & numbers to know

When this topic comes up

  • “How does the database find a row on disk?”
  • “Why is this index scan reading so many pages?”
  • “UUID or auto-increment primary key?”
  • Clustered vs non-clustered indexes
  • Buffers in EXPLAIN

Benchmarks & rules of thumb

8 kB -
PostgreSQL and SQL Server page size
16 kB -
InnoDB page size
~2 kB -
value size at which PostgreSQL TOASTs data
3–4 -
B-tree levels for millions of rows

Common mistakes & follow-ups

Common interview mistakes

  • Expecting 1,000 index lookups to cost 1,000 rows' worth of I/O, when they can cost 1,000 pages.
  • Using random UUIDs as InnoDB primary keys on a high-insert table and seeing write throughput fall as it grows.
  • Adding an index on a frequently updated column and losing HOT updates.

Likely interviewer follow-ups

  • Walk me through how PostgreSQL finds a row using an index.
  • What's a clustered index, and how does InnoDB use it?
  • Why can a table grow even when the row count stays the same?
Interview tip: Explain lookups in pages, not rows: index pages, then a heap page per row. Thinking in pages is what makes your explanations of EXPLAIN output convincing.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply How Databases Store Data on Disk (Pages, Blocks, Heap, B-Trees) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Schema Evolution & Zero-Downtime Column Migrations
Next topic
How Indexes Work & The Read vs Write Trade-off