Improving Query Performance in PostgreSQL
Amy McCarty
Instructor
System | Front end steps | Back end processes | |
---|---|---|---|
1 | Parser | Send query to database | Checks syntax. Translates SQL into more computer friendly syntax based on system stored rules. |
2 | Planner & Optimizer | Assess and optimize query tasks | Uses database stats to create query plan. Calculates costs and chooses the best plan. |
3 | Executor | Return query results | Follows the query plan to execute the query. |
Responsive to SQL structure changes
SELECT * FROM pg_class
WHERE relname = 'mytable'
-- sample of output columns
| relname | relhasindex |
SELECT * FROM pg_stats
WHERE tablename = 'mytable'
-- sample of output columns
null_frac | avg_width | n_distinct |
EXPLAIN
SELECT * FROM cheeses
Seq Scan on cheeses
(cost=0.00..10.50 rows=5725 width=296)
Seq Scan on cheeses (cost=0.00..10.50 rows=5725 width=296)
Seq Scan on cheeses (cost=0.00..10.50 rows=5725 width=296)
..10.50 : total time
total time = start up + run time
Seq Scan on cheeses (cost=0.00..10.50 rows=5725 width=296)
EXPLAIN
SELECT * FROM cheeses WHERE species IN ('goat','sheep')
Seq Scan on cheeses (cost=0.00..378.90 rows=3 width=118)
-> Filter: (species = ANY ('{"goat","sheep"}'::text[]))
EXPLAIN
SELECT * FROM cheeses WHERE species IN ('goat','sheep') -- index on species column
Bitmap Index Scan using species_idx on cheeses (cost=0.29..12.66 rows=3 width=118)
Index Cond: (species = ANY ('{"goat","sheep"}'::text[]))
Improving Query Performance in PostgreSQL