Concept
Index Types: B-Tree vs Hash
Without an index, the SQL planner must run a Sequential Scan (Seq Scan), checking every page on disk sequentially.
Creating an index structures data to avoid disk page scans:
- B-Tree (Default): Balanced tree structure. Supports equality (
=) and range queries (<,>,BETWEEN). - Hash: Stores key-value mappings. Extremely fast for exact equality (
=) checks, but cannot perform range scans.
Query Plan Analysis: EXPLAIN ANALYZE
To diagnose slow SQL queries, prepend the query with EXPLAIN ANALYZE. This executes the query and prints the planner choice and timing statistics:
-- Find user profile detailsEXPLAIN ANALYZE SELECT * FROM users WHERE email = 'ada@example.com';
Postgres receives the SQL query. The parser compiles the SQL into an AST, checking permissions and schemas.