What is the difference between a sequential scan and an index scan?
IntermediateConceptPostgreSQL
Answer
Short answer
A sequential scan reads every row of a table to find matches. An index scan uses an index to jump straight to the matching rows. Index scans win when you need a small fraction of rows; sequential scans can actually be faster when you need a large share of the table.
Example
EXPLAIN SELECT * FROM orders WHERE id = 42; -- Index Scan using orders_pkey
EXPLAIN SELECT * FROM orders WHERE total > 0; -- Seq Scan (almost every row matches)
Other scan types you'll see
| Plan node | Meaning |
|---|---|
| Index Only Scan | All needed columns are in the index — table not touched |
| Bitmap Index/Heap Scan | Collects matching locations from the index, then reads pages in order (medium selectivity) |
Why Postgres sometimes ignores your index
- The query returns too many rows (seq scan is cheaper).
- The column is wrapped in a function:
WHERE lower(email) = ...needs an expression indexON (lower(email)). - Stale statistics →
ANALYZE. - Type mismatch (comparing text to integer).
What to say in the interview
"A seq scan reads the whole table; an index scan seeks directly to matching rows. The planner chooses based on selectivity and statistics, so an ignored index usually means low selectivity, a function on the column needing an expression index, or stale stats."
More on PostgreSQL
How do you set up PostgreSQL and log in with psql?BeginnerHow do you create a database, tables, users and query data in PostgreSQL?BeginnerHow do you back up and restore a PostgreSQL database?BeginnerWhat is PostgreSQL and why is it so popular?BeginnerHow is PostgreSQL organised: cluster, database, schema and table?BeginnerHow do you connect to PostgreSQL from the command line?Beginner