Indexes
An orders table holds a million rows. You ask for the ten that belong to one customer with WHERE user_id = 7, and the engine reads all million, row by row, checking each one, to hand back ten.
- ▸A sorted side-copy of one column turns reading a million rows into a few quick hops.
- ▸Build that shortcut and the engine still reads the whole table when a query returns most rows.
- ▸Filter on just the second column: few customers, the sorted copy skips through; thousands, the engine reads the whole table.
An orders table holds a million rows, and you want the few that belong to customer 7: SELECT * FROM orders WHERE user_id = 7. With nothing prepared, the engine has no choice but to read every row, all million, checking user_id on each and keeping the handful that match. Reading the whole table top to bottom this way is a sequential scan, and its cost grows with the size of the table, not the size of the answer.
Now build a sorted side-structure: a separate list of every user_id value, kept in order, each entry holding a pointer back to its row. That structure is an index. Because it is sorted, the engine jumps straight to the user_id = 7 entries in a few steps, the way you find a word in a dictionary, then follows each pointer to fetch the row. Reading the index and following its pointers is an index scan.
PostgreSQL stores a table in fixed 8 kB pages, many rows to a page, and reads it a page at a time. For a handful of rows scattered over the table, PostgreSQL collects the pointers first and then reads each table page once, a bitmap scan, but the path is the same: index first, then the rows. The table never moved; the index is a second, sorted view onto it.