Video in progress
There is one composite index on the columns `(last_name, first_name)`. Will the query `WHERE first_name = 'Aziz'` use it?
Usually it won't use it efficiently. A composite B-tree is sorted by the first column, then by the second, so the index works well for conditions that start with the leftmost column(s). To search by the second column alone you need a separate index.
📖 Answer
Inside the index the data is ordered roughly like this:
(Aliyev, Aziz) (Aliyev, Bobur) (Karimov, Aziz) (Karimov, Dilshod) (Toshev, Aziz) ...
The "Aziz" entries are scattered across the whole index, so you can't find them quickly.
CREATE INDEX idx_people_name ON people(last_name, first_name);
WHERE last_name = 'Karimov' -- works
WHERE last_name = 'Karimov' AND first_name = 'Aziz' -- the best case
WHERE first_name = 'Aziz' -- not efficient
WHERE last_name LIKE 'Ka%' AND first_name = 'Aziz' -- a range on the first column, then a filter
PostgreSQL 18 added "skip scan": if the first column has few distinct values, it can use the index for the second column as well. But don't design around that.
When I choose the column order, I think like this: the column that is almost always queried with = goes first. A range (>, BETWEEN) or ORDER BY column comes after. For example, for WHERE user_id = ? ORDER BY created_at DESC the index is (user_id, created_at).
Sign up to mark studied questions and save your progress.