What is Index Scan in PostgreSQL: Explanation and Example
index scan is a method to find rows in a table by searching an index instead of scanning the whole table. It speeds up queries by quickly locating data using the index structure.How It Works
Imagine you have a big book and you want to find a specific topic. Instead of reading every page, you use the index at the back to jump directly to the pages you need. An index scan in PostgreSQL works the same way. It uses a special data structure called an index to quickly find rows that match your query.
When you run a query with conditions on indexed columns, PostgreSQL can use the index to find matching rows without checking every row in the table. This saves time, especially for large tables. The database looks up the index, finds pointers to the matching rows, and then fetches those rows from the table.
Example
This example shows how PostgreSQL uses an index scan to find rows with a specific value in an indexed column.
CREATE TABLE employees ( id SERIAL PRIMARY KEY, name TEXT, department TEXT ); INSERT INTO employees (name, department) VALUES ('Alice', 'Sales'), ('Bob', 'Engineering'), ('Carol', 'Sales'), ('Dave', 'Engineering'); CREATE INDEX idx_department ON employees(department); EXPLAIN ANALYZE SELECT * FROM employees WHERE department = 'Sales';
When to Use
Use an index scan when you want to speed up queries that filter rows based on indexed columns. It is especially helpful for large tables where scanning every row would be slow.
For example, if you often search for employees by department or customers by city, creating an index on those columns lets PostgreSQL quickly find matching rows using an index scan. However, for very small tables or queries that return most rows, a full table scan might be faster.
Key Points
- An
index scanuses an index to find rows quickly without scanning the whole table. - It improves query speed for large tables with selective filters.
- PostgreSQL decides automatically when to use an index scan based on query cost.
- Indexes add some overhead for inserts and updates, so use them wisely.