How PostgreSQL Indexing Works: A Simple Crash Course
Imagine you run an online shop in Dhaka. Your database stores 200,000 orders. A customer opens their order history. Your app must find only that customer’s orders.
How does PostgreSQL find them? Does it check the whole table? Can it take a shortcut?
This guide explains that shortcut with a small example, six diagrams, and SQL you can run yourself. You will learn what an index stores, how a B-tree works, and how to check whether an index helps.
1. Start with a simple question
Here are six example orders. These are small teaching examples; we will create a larger practice table later.
Order ID | Customer ID |
|---|---|
101 | 7 |
102 | 42 |
103 | 15 |
104 | 9 |
105 | 42 |
106 | 28 |
We want orders from customer 42:
SELECT id, created_at, total_taka
FROM shop_index_demo_orders
WHERE customer_id = 42;In our small example, orders 102 and 105 match. Now let’s see how PostgreSQL could find them.
2. Without a suitable index: read and check
Without a useful index for this query, PostgreSQL can read the table and check each row:
Is the customer ID 42? Keep the row.
Is it another customer? Skip the row.
Continue until the scan is complete.
This is a sequential scan, usually shown as Seq Scan in a query plan. PostgreSQL reads table pages, which contain rows. A page is a small block of stored data.
Checking six rows is easy. Checking 200,000 rows to return just 10 can involve a lot of extra work. This is where an index may help.
3. What is a PostgreSQL index?
An index is a separate data structure that helps PostgreSQL find data.
Think of a book’s index. To find “payments,” you look up the word and get a page number. You then open that page. You do not read the whole book.
For our orders query, the database index contains customer IDs and references to matching table rows. A reference tells PostgreSQL where to look. It is a physical row location, not simply the order’s id value.
CREATE INDEX shop_index_demo_customer_idx
ON shop_index_demo_orders (customer_id);Here, shop_index_demo_customer_idx is the index name. The table is shop_index_demo_orders, and the indexed column is customer_id.
Creating this index does not rearrange the table by customer ID. It creates a separate way to find the rows. You keep writing the same SELECT query. PostgreSQL decides whether using the index is useful.
4. How does the B-tree find customer 42?
The default PostgreSQL index type is B-tree. You do not need to write USING btree in the command above.
A B-tree keeps keys in order across index pages. It can narrow a search through a small number of levels instead of checking every table row.
Here is a simplified lookup:
Read the root page. This is the starting point. Choose the path that can contain 42.
Follow the path. Large trees have extra branch pages that narrow the search.
Find 42 on a leaf page. Leaf pages contain keys and row references. Read the matching references, continuing across leaf pages if needed.
Fetch the table rows. In an ordinary index scan, PostgreSQL visits those locations, checks which row versions the query can see, and reads the requested data.
This picture shows the idea, not PostgreSQL’s exact page layout. A very small tree can have just one page that acts as both root and leaf.
Also, finding an index entry is only part of the work. If one customer has thousands of orders spread across many table pages, fetching all those rows still takes work.
5. Practice with 200,000 orders
Run this in a practice database. Use a new table name if shop_index_demo_orders already exists. The setup is meant to run once.
We will create 200,000 orders for 20,000 customers. Each customer gets exactly 10 orders. Prices use whole taka to keep the example simple.
CREATE TABLE shop_index_demo_orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id integer NOT NULL,
created_at timestamptz NOT NULL,
total_taka integer NOT NULL
);
INSERT INTO shop_index_demo_orders
(customer_id, created_at, total_taka)
SELECT
1 + ((n - 1) % 20000),
TIMESTAMPTZ '2025-01-01 00:00:00+00'
+ n * INTERVAL '1 minute',
100 + (n % 5000)
FROM generate_series(1, 200000) AS numbers(n);
ANALYZE shop_index_demo_orders;generate_series gives us numbers from 1 to 200,000. We use them to make sample rows. ANALYZE collects statistics that help PostgreSQL choose a query plan.
The primary key already creates an index on id. But our query searches by customer_id. An index on one column does not automatically make searches on every other column fast.
Check the query before adding the customer index
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at, total_taka
FROM shop_index_demo_orders
WHERE customer_id = 42;You will likely see Seq Scan or a parallel sequential scan. The result contains 10 orders, but the scan checks many more rows to find them.
Add the customer index
CREATE INDEX shop_index_demo_customer_idx
ON shop_index_demo_orders (customer_id);Now run the exact same EXPLAIN (ANALYZE, BUFFERS) query again.
You may see Index Scan. You may instead see Bitmap Index Scan with Bitmap Heap Scan. Both can use the new index. A bitmap plan first collects matching row locations, then reads the relevant table pages in physical order.
The exact plan and time depend on your data, statistics, settings, and machine. There is no fixed speed improvement for every database.
6. Read EXPLAIN without getting lost
A query plan can look complicated. Start with these parts:
Plan text | Simple meaning |
|---|---|
| Read table pages and check rows. |
| Use an index and fetch matching table rows. |
| A condition used to search the index. |
| An extra check applied to candidate rows. |
| This node returned 10 rows in one run. |
| Rows checked and rejected by that filter. |
| Information about data blocks accessed. |
| Time spent executing the statement. |
Read actual row counts carefully. If a node has several loops, the shown rows are an average per loop. A plan node’s row count is not always the final query’s total.
In buffer output, shared hit means PostgreSQL already had the block in its shared buffer cache. A shared read means PostgreSQL brought it into those buffers. The operating system may still have served it from memory.
Run each query several times under similar conditions. A later run can benefit from cached data. Creating an index can also warm the cache. Do not use one run to claim “100 times faster.”
Remember: EXPLAIN ANALYZE actually runs the statement. Plain EXPLAIN shows the estimated plan without running it.
7. Need the latest orders? Use a composite index
Now the app wants the latest three orders for customer 42:
SELECT id, created_at, total_taka
FROM shop_index_demo_orders
WHERE customer_id = 42
ORDER BY created_at DESC, id DESC
LIMIT 3;The customer index helps find that customer’s orders. PostgreSQL may still need to sort them.
A composite index uses more than one column:
CREATE INDEX shop_index_demo_customer_recent_idx
ON shop_index_demo_orders
(customer_id, created_at DESC, id DESC);Read this index order from left to right:
First, group entries by customer.
Inside each customer, put newer orders first.
If two orders have the same time, put the larger ID first.
With a suitable plan, PostgreSQL can read the first three matches in the required order and stop early. Run EXPLAIN (ANALYZE, BUFFERS) on this query to inspect your plan.
The practice table has 10 orders per customer. The diagram uses shorter dates to explain the sorting idea; it does not show literal output from the generated table.
Column order matters. The latest three orders across all customers is a different query. An index starting with the date is usually a better fit for that task.
Always write ORDER BY when result order matters. Having an index alone does not promise a particular result order.
8. Why might PostgreSQL ignore an index?
An index is an option. PostgreSQL’s planner estimates the work of possible plans and chooses one.
Try this query:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at, total_taka
FROM shop_index_demo_orders
WHERE customer_id <= 18000;This returns 180,000 rows: 90% of our sample table.
When nearly every row is needed, reading the table in order may cost less than using the index and fetching many separate rows. A sequential scan can be the right choice. Very small tables can also be cheap to scan.
PostgreSQL also considers statistics, row locations, ordering, limits, and cost settings. A high match count is a useful explanation, not the only reason for a sequential scan.
9. What does an index cost?
Indexes use disk space. PostgreSQL must also maintain them when data changes. Inserts add index entries. Updates and deletes can lead to extra work and later cleanup.
That is why “add an index to every column” is a poor default. Start with a real query users run often. Check its filters and sorting. Add a suitable index, then measure the difference.
For a large live table, plan index creation carefully. Ordinary CREATE INDEX blocks writes while it builds. PostgreSQL also offers CREATE INDEX CONCURRENTLY, with different costs and restrictions. Our exercise uses ordinary creation on a practice table.
10. Common questions
Does a primary key create an index?
Yes. PostgreSQL normally creates a unique B-tree index to support a primary key. Our primary key index helps searches by id, while we added another index for searches by customer_id.
Does a foreign key create an index too?
A foreign key does not automatically create an index on the referencing columns. Whether to add one depends on your queries and how you update or delete related rows.
Is a row reference the same as the primary key?
No. A B-tree row reference identifies a physical location in the table. Do not picture PostgreSQL looking up an order ID in a second index for every ordinary index scan.
What is an index-only scan?
Sometimes all the columns a query needs are stored in the index. PostgreSQL may return them using an index-only scan. It can avoid a table visit when the visibility map says the relevant table page is all-visible. Otherwise it still checks the table. Look at Heap Fetches in the plan.
Is B-tree the only index type?
No. PostgreSQL also has types such as GIN, GiST, and BRIN. Start by learning B-tree for common equality, range, and sorting queries. Choose other types when your data and query need them.
Should I keep both customer indexes from this exercise?
Not automatically. The composite index also starts with customer_id, so it may serve customer-only lookups too. Review real usage, index size, and write cost before keeping both. This exercise creates them separately to teach each step.
11. Check your understanding
Before adding an index to your next feature, answer these questions:
Which query needs help?
Which columns does it filter or sort by?
Does it need a few rows or most of the table?
What does its current plan show?
Did the new index reduce the work enough to justify its cost?
For our shop, the query is clear: find one customer’s orders. A customer index gives PostgreSQL a way to find their row locations. A composite index can also help return their newest orders first.
The practical habit is simple: write the query, read the plan, add a suitable index, and measure again.
I hope you find it well, if you have any question about me, you can email me. Or you can give some feedback in one minute in the guestbook
Comments
Join the discussion. Sign in with Google to post; your email is never shown.