B-Tree Indexes — Complete Guide
B-Tree Indexes — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 21 of 100
B-Tree Indexes
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — Indexing & Performance
What is this?
B-Tree is PostgreSQL default index type — balanced tree good for equality and range on scalar columns. CREATE INDEX builds a separate structure pointing to heap rows.
Why should you care?
PostgresVerse order lookup by customer_id without an index scans millions of rows; B-Tree makes WHERE customer_id = ? milliseconds.
See it live — copy this example
Run in pgAdmin or psql.
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC);
SELECT order_id FROM orders
WHERE customer_id = 501
ORDER BY created_at DESC
LIMIT 5;
What happened?
- Composite index leads with customer_id then created_at descending.
- The query filters one customer and walks the index in sort order — often no extra sort step.
Practice next
- Run EXPLAIN on the SELECT before creating the index.
- CREATE INDEX and run EXPLAIN again.
- Note Index Scan vs Seq Scan in the plan.
- Create UNIQUE INDEX on customers(email).
- Use CONCURRENTLY in production to avoid long write locks.
Remember
B-Tree suits =, <, >, BETWEEN, ORDER BY on scalars. Composite index column order matters. Indexes speed reads and slow writes slightly.
PostgresVerse order history index
Support portal loads last five orders per customer instantly after composite B-Tree deploy.
Outcome: Seq Scan disappears from pg_stat_statements top offenders.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!