← العودة إلى الدورة: SQL and databases from scratch

Indexes and performance with EXPLAIN

الفيديو قريبًا

With 12 orders any query is instant. With 50 million, a poorly thought-out query can take minutes. Indexes are the main tool for keeping queries fast as tables grow. An index works like the alphabetical index of a book: instead of reading every page to find a word, you go straight to the indicated page. In a database, without an index the engine has to read the whole table row by row (sequential scan); with an index, it finds the wanted rows almost immediately.

Creating an index

The default type in PostgreSQL is the B-tree, an ordered tree that serves equality, ranges and sorting. The syntax is CREATE INDEX name ON table (column). PostgreSQL automatically creates an index for each primary key and each UNIQUE constraint, but not for foreign keys: if you query or join a lot by a foreign column, create the index yourself. Indexes are not free: they take space and slow down INSERT, UPDATE and DELETE, because they have to be kept up to date. They are created where reads justify them, not on every column.

sql
-- A bigger practice table: 500,000 fake orders (PostgreSQL)
CREATE TABLE big_orders AS
SELECT g AS order_id,
       (random() * 1000)::INTEGER AS customer_id,
       DATE '2023-01-01' + (random() * 700)::INTEGER AS order_date,
       (random() * 500)::NUMERIC(10,2) AS total
FROM generate_series(1, 500000) AS g;

ANALYZE big_orders;   -- refresh the statistics the planner uses

-- Without an index
EXPLAIN ANALYZE SELECT * FROM big_orders WHERE customer_id = 42;

Reading EXPLAIN

EXPLAIN shows the execution plan: the recipe the optimizer chooses to solve your query. EXPLAIN ANALYZE also actually runs the query and adds real times; careful, because it also runs INSERT, UPDATE and DELETE (wrap them in BEGIN and ROLLBACK). The key nodes: Seq Scan is reading the whole table; Index Scan and Index Only Scan use an index; Bitmap Heap Scan is an intermediate variant; Nested Loop, Hash Join and Merge Join are JOIN strategies. Look at rows (estimated rows) and actual time (real time in milliseconds). Without an index you will see something like Seq Scan on big_orders, with Filter: (customer_id = 42) and a time of tens of milliseconds.

sql
CREATE INDEX idx_big_orders_customer ON big_orders (customer_id);

-- Same query: now the plan should use the index (Bitmap Index Scan or Index Scan)
EXPLAIN ANALYZE SELECT * FROM big_orders WHERE customer_id = 42;

-- A composite index: useful for WHERE customer_id = ? AND order_date >= ?
CREATE INDEX idx_big_orders_customer_date ON big_orders (customer_id, order_date);

EXPLAIN SELECT * FROM big_orders
WHERE customer_id = 42 AND order_date >= '2024-01-01';

-- Remove what you do not need
DROP INDEX idx_big_orders_customer;

In the composite index, column order matters: it serves filtering by the first column, or by the first and second, but not by the second alone. The practical rule is to put first the column compared with equality and then the range one. If you look at the plan after creating the index, the time should drop from tens of milliseconds to less than one.

When the index is not used

  • The table is small: reading it all is cheaper (that is why in the 12-order shop you will see Seq Scan even with an index).
  • You apply a function to the column: WHERE EXTRACT(YEAR FROM order_date) = 2024 does not use an index on order_date; rewrite as order_date >= '2024-01-01' AND order_date < '2025-01-01'.
  • LIKE with a leading wildcard: LIKE '%mouse' cannot use the B-tree index.
  • The condition returns a large part of the table: the engine prefers to read it sequentially.
  • The types do not match and force a conversion of the column.

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →