Introduction
We want to find data quickly in a database. Sequential scan and index scan are two ways to look for data.
Jump into concepts and practice - no test required
We want to find data quickly in a database. Sequential scan and index scan are two ways to look for data.
EXPLAIN SELECT * FROM table_name WHERE column_name = value;
EXPLAIN SELECT * FROM employees WHERE id = 5;
EXPLAIN SELECT * FROM employees;
CREATE INDEX idx_name ON employees(name);
EXPLAIN SELECT * FROM employees WHERE name = 'Alice';
This creates a small employees table, adds three rows, and shows how PostgreSQL finds the employee with id 2.
CREATE TABLE employees (id SERIAL PRIMARY KEY, name TEXT, age INT); INSERT INTO employees (name, age) VALUES ('Alice', 30), ('Bob', 25), ('Carol', 27); EXPLAIN SELECT * FROM employees WHERE id = 2;
A sequential scan reads every row one by one. It is simple but can be slow on big tables.
An index scan uses a special data structure to jump directly to matching rows. It is faster for selective queries.
PostgreSQL decides automatically which scan to use based on table size and query.
Sequential scan reads all rows; good for small tables or full reads.
Index scan uses an index to find rows faster; good for selective queries.
Use EXPLAIN to see which scan PostgreSQL chooses.
sequential scan do in PostgreSQL?EXPLAIN command shows how PostgreSQL executes a query, including scan type.users(id SERIAL PRIMARY KEY, name TEXT) with 1 million rows, which scan is PostgreSQL likely to use for this query?SELECT * FROM users WHERE id = 500000;id, which has an index, and the table is large (1 million rows).SELECT * FROM orders WHERE customer_id = 123;customer_id, PostgreSQL must scan all rows sequentially.customer_id -> Option Aproducts with millions of rows and an index on category_id. You run:SELECT * FROM products WHERE category_id IN (1, 2, 3, 4, 5);