Video in progress

When are Seq Scan, Index Scan, Index Only Scan and Bitmap Heap Scan chosen?

If you need many rows, Seq Scan is cheap. For few rows, Index Scan. If all the needed columns are in the index and the pages are clean in the visibility map, Index Only Scan. For a medium number of rows, or when several indexes are combined, Bitmap Heap Scan.

📖 Answer

The planner computes the cost of each option and takes the cheapest. The main question is how much of the table you need.

Seq Scan reads the table sequentially from start to end. If a noticeable share of the rows is needed (roughly more than 5-10%) or the table is small, this is the cheapest. Don't panic the moment you see a Seq Scan.

Index Scan finds rows in the index and goes to the heap for each one. Every trip is a random read, so it's great for a few rows and gets expensive at thousands of rows.

Index Only Scan: the needed columns are in the index, so it may not have to visit the heap. But to check row visibility it looks at the visibility map: if a page isn't "all-visible", it still goes to the heap. Heap Fetches in the plan shows that number; if it's large, VACUUM may not be keeping up.

Bitmap Index Scan + Bitmap Heap Scan first gathers a map of matching pages from the index, then reads the heap in page order. Random reads are reduced. It can combine two indexes with BitmapAnd/BitmapOr:

-- if there are separate indexes on status and region
SELECT * FROM orders WHERE status = 'NEW' OR region_id = 7;
-- BitmapOr -> Bitmap Heap Scan

On an SSD the default random_page_cost of 4 is too high, and lowering it to around 1.1 makes the planner more inclined to use indexes.