Thuta Learning
SQL
AdvancedData & DatabasesBeginner

SQL Indexes and Query Performance

SQLLesson 3035 min

What you'll walk away with

  • Tell a Seq Scan from an Index Scan in EXPLAIN output
  • Pick a composite index's column order to match the WHERE and ORDER BY of a query
  • Recognise when wrapping a column in a function blocks an index, and fix it with an expression index or a range condition
  • Weigh the write and storage cost that every extra index adds

Explain it simply

Explain it simply

Imagine finding every page that mentions "foreign key" in a thick book. You could turn every page from 1 to the end, but it takes a long time. The index at the back of the book lists words in alphabetical order with page numbers, so you get there in seconds.

A database index works the same way. It is a separate structure that keeps column values sorted, and each value points to where its row lives in the table. The trade-off is the same as with the book: every new page means updating the index, and every new row means updating the database index too.

Problem → Why → Solution

The problem: a page that slows down as data grows

An online shop's "My orders" page shows a customer's ten latest orders. At launch there are only a few hundred orders and the page is fast. A year later there are millions, every page load takes seconds and the database CPU stays high, even though nobody changed a single character of the query.

EXPLAIN shows why. PostgreSQL reads every order from start to finish (a Seq Scan), throws away the rows that do not belong to customer 42, sorts what is left, and only then keeps ten.

my-orders.sql
-- Runs on every visit to "My orders"
SELECT id, total, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;
-- Plan: Limit -> Sort -> Seq Scan on orders (reads the whole table)

Why it gets slower with the data

Without an index PostgreSQL has only one option: read every row and test the condition. The work grows with the size of the table, not with the ten rows you actually want. An index lets it jump to those ten rows, so the work stays roughly the same as the table grows.

Core concept: shape the index after the query

PostgreSQL's default index type is the B-tree. It keeps values sorted in a tree, so it can help with =, <, >, BETWEEN, ORDER BY, and prefix searches like 'abc%' (which may need the C collation or text_pattern_ops). For every query the planner estimates how many rows will come back and picks the cheapest plan among a Seq Scan, an Index Scan and a Bitmap Scan. An index existing does not guarantee it will be used.

1. Selectivity matters

customer_id = 42 picks about 40 rows out of 20,000, so an index helps a lot. total > 5 matches almost every row, and reading the table sequentially once is cheaper than jumping through an index row by row, so the planner chooses a Seq Scan.

2. Column order matters in a composite index

An index on (customer_id, created_at DESC) is sorted by customer_id first, and newest-first within each customer. "Customer 42's latest ten" therefore sits side by side in the index and no Sort step is needed. The usual rule: columns tested with = go first, and the range or sort column goes after them.

3. An index only knows the column value

With an index on created_at, WHERE created_at::date = '2026-01-05' still cannot use it, because the index does not store cast date values. Write a range condition (>= and <) that leaves the column bare, or build an expression index on the expression itself, such as lower(email).

4. Every index has a cost

Every INSERT, UPDATE and DELETE must also update every relevant index, and each index takes disk space. Add indexes for queries that run often, and drop the ones nothing uses.

Plan nodeWhat it means
Seq ScanReads the table start to end and checks a Filter
Index ScanSearches the index, then fetches matching rows from the table
Bitmap Heap ScanCollects row locations from an index, then reads table pages in order
Index Only ScanEvery needed column is in the index, so the table is barely touched
Mental model: from the query to the index
  1. EXPLAIN the slow query
  2. Put = columns first in the index
  3. Put the range or sort column next
  4. Run EXPLAIN again to confirm

Design an index for a query that runs often, not for a column in isolation.

General pattern

sql
CREATE [UNIQUE] INDEX index_name
ON table_name (equality_col, range_or_sort_col [DESC]);

CREATE INDEX index_name ON table_name (lower(text_col));   -- expression
CREATE INDEX index_name ON table_name (col) WHERE flag;    -- partial

EXPLAIN [ANALYZE] SELECT ... ;   -- show the chosen plan
DROP INDEX index_name;

Equality columns go first, then the range or sort column. An expression index serves conditions that wrap a column in a function; a partial index suits queries that always look at the same subset of rows. EXPLAIN shows the estimated plan, while EXPLAIN ANALYZE actually runs the query and reports real timings.

Speeding up the "My orders" query

The example uses a table of 20,000 orders for 500 customers, with statistics prepared by ANALYZE, and compares the plan before and after adding the index. Cost numbers are the planner's estimates and change with data, statistics and PostgreSQL version, so read the output as a sample. What matters is the shape of the plan: Sort plus Seq Scan turns into a single Index Scan.

orders-index.sql
-- 1. How does PostgreSQL run the query today?
EXPLAIN
SELECT id, total, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;

-- 2. Add an index shaped like the query
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC);

-- 3. Ask again
EXPLAIN
SELECT id, total, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;

Code breakdown

  1. Ask for the planEXPLAIN

    EXPLAIN shows the plan the planner would choose without running the query. The first plan contains Seq Scan on orders with Filter: (customer_id = 42).

  2. The query being tunedWHERE customer_id = 42

    This is an equality condition, so it belongs in the index's first column. After the index exists it shows up in the plan as Index Cond instead of Filter.

  3. Index shaped like the queryON orders (customer_id, created_at DESC);

    Each customer's orders are already stored newest-first in the index, so PostgreSQL reads the first ten entries and stops. That is why the Sort node disappears from the second plan.

  4. LIMIT stops earlyLIMIT 10;

    When rows come out of the index already in order, LIMIT stops after ten. Without the index every matching row has to be sorted before the first ten can be taken.

You should see
-- plan before the index (cost numbers are estimates and will differ)
 Limit  (cost=398.86..398.89 rows=10 width=21)
   ->  Sort  (cost=398.86..398.96 rows=40 width=21)
         Sort Key: created_at DESC
         ->  Seq Scan on orders  (cost=0.00..398.00 rows=40 width=21)
               Filter: (customer_id = 42)

-- plan after the index
 Limit  (cost=0.29..37.45 rows=10 width=21)
   ->  Index Scan using idx_orders_customer_created on orders
         (cost=0.29..148.93 rows=40 width=21)
         Index Cond: (customer_id = 42)

When an index exists but is not used

The snippet below builds an index on created_at and compares two queries. The first casts the column with ::date and gets a Seq Scan; the second expresses the same day as a range on the bare column and gets an Index Scan. The plans in the comments are shortened from a run on PGlite (PostgreSQL 18).

sargable.sql
CREATE INDEX idx_orders_created ON orders (created_at);

-- Function on the column: the index cannot help
EXPLAIN SELECT id FROM orders WHERE created_at::date = '2026-01-05';
-- Seq Scan on orders  Filter: ((created_at)::date = '2026-01-05'::date)

-- Same day as a range on the bare column
EXPLAIN SELECT id FROM orders
WHERE created_at >= '2026-01-05' AND created_at < '2026-01-06';
-- Index Scan using idx_orders_created on orders

The leftmost-column rule and PostgreSQL 18

An index on (customer_id, created_at) works best for queries that filter on customer_id. PostgreSQL 18 added B-tree skip scan, so such an index can sometimes serve a query without the first column, but it pays off mainly when that first column has few distinct values. Do not rely on it; check with EXPLAIN. MySQL and SQL Server follow much the same column-order rule for composite indexes.

In real projects

In real projects

In production nobody adds indexes by guesswork. Teams find the most expensive queries with the pg_stat_statements extension or the slow-query log, read their plans with EXPLAIN (ANALYZE, BUFFERS), and only then decide. PostgreSQL does not create indexes for foreign key columns automatically (it does for primary keys and UNIQUE constraints), so indexing join columns such as orders.customer_id is one of the most common fixes.

On a large, busy table a plain CREATE INDEX blocks writes until the build finishes, which is why teams usually run CREATE INDEX CONCURRENTLY. It takes longer, does not block writes, and cannot run inside a transaction block. They also review pg_stat_user_indexes for indexes with idx_scan = 0 and drop the ones nobody needs.

Common mistakes

Common mistakes

Choosing composite column order without looking at the query

Build it the other way round, (created_at, customer_id), and customer 42's rows are scattered across the whole index, so "one customer's latest ten" cannot be found efficiently. Put the column tested with = first.

Indexing every column "just in case"

With five indexes, one INSERT writes to six structures: the table and five indexes. Reads do not get faster, writes slow down and disk fills up. Only add an index for a query that really runs.

Wrapping the indexed column in a function

WHERE lower(email) = ... or WHERE created_at::date = ... cannot use a plain index on the column. Rewrite it as a range, or create an index on that exact expression.

Panicking about a Seq Scan on a tiny table

On a table with a handful of rows, reading one or two pages directly is cheaper than going through an index, so a Seq Scan is the right choice. Judge plans on data close to production size, after ANALYZE.

Mini challenge

Case-insensitive unique emails

The users table already contains 'susu@mail.com'. Create an index so nobody can register 'SuSu@Mail.com' as a second account, and write the login lookup so it can use that index.

  • Create a UNIQUE expression index on lower(email)
  • Try a duplicate insert inside a DO block and catch unique_violation
  • Look up a user with WHERE lower(email) = lower('...')
  • List the users table's indexes from pg_indexes
unique-email.sql
-- users(id, email, full_name) already has two rows.

-- TODO 1: one account per email, ignoring letter case

-- TODO 2: prove a case-only duplicate is rejected without stopping the script
DO $$
BEGIN
  -- TODO: insert 'SuSu@Mail.com'
EXCEPTION WHEN unique_violation THEN
  RAISE NOTICE 'duplicate rejected';
END $$;

-- TODO 3: find the user for 'KOKO@mail.com' in a way the index can serve

-- TODO 4: list index names and definitions for the users table

Expected: A NOTICE says duplicate rejected, the lookup returns id 2, Ko Ko, and the final query lists two indexes: users_email_lower_key and users_pkey.

Show hint

The index is only usable when the WHERE expression matches the indexed expression exactly. A plain UNIQUE (email) would treat 'SuSu@Mail.com' and 'susu@mail.com' as different and let the duplicate in.

Show solution
unique-email.sql
-- 1. One account per email, ignoring letter case
CREATE UNIQUE INDEX users_email_lower_key ON users (lower(email));

-- 2. A duplicate that differs only in case must be rejected
DO $$
BEGIN
  INSERT INTO users (email, full_name) VALUES ('SuSu@Mail.com', 'Su Su 2');
  RAISE NOTICE 'duplicate was accepted';
EXCEPTION WHEN unique_violation THEN
  RAISE NOTICE 'duplicate rejected';
END $$;

-- 3. Login lookup written so the expression index can serve it
SELECT id, full_name FROM users WHERE lower(email) = lower('KOKO@mail.com');

-- 4. Confirm what exists
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'users'
ORDER BY indexname;

Quick quiz 1 / 3

A query uses WHERE status = 'paid' AND created_at >= '2026-01-01' ORDER BY created_at. Which index fits best?

Quick quiz 2 / 3

There is a plain B-tree index on users.email. Which condition cannot use it directly?

Quick quiz 3 / 3

On a 50-row table, EXPLAIN still shows a Seq Scan after you created an index. What is the most likely reason?

What to remember

  • An index jumps straight to rows but slows every write and takes disk space
  • In a composite index put = columns first and the range or sort column after them
  • Wrapping a column in a function blocks a plain index; use a range or an expression index
  • EXPLAIN costs are estimates: read the plan's shape and confirm with EXPLAIN ANALYZE
  • PostgreSQL does not index foreign key columns automatically

PostgreSQL Indexes — PostgreSQL

PostgreSQL Indexes — PostgreSQL

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

SQL Indexes and Query Performance | Thuta Learning