How PostgreSQL processes a query (parser, planner, executor) - Performance & Efficiency
When PostgreSQL runs a query, it goes through several steps that take time. Understanding how these steps grow with bigger queries helps us know how fast or slow the database might be.
We want to see how the work done changes as the query or data size grows.
Analyze the time complexity of PostgreSQL processing a simple SELECT query.
-- Simplified flow of query processing
BEGIN;
PREPARE stmt AS SELECT * FROM employees WHERE department_id = $1;
EXECUTE stmt(10);
COMMIT;
This code prepares and runs a query to get employees from one department.
PostgreSQL does several steps for each query:
- Primary operation: Parsing the query text, planning the best way to get data, and executing the plan.
- How many times: Each step happens once per query, but execution may scan many rows depending on data size.
As the query or data grows, the work changes like this:
| Input Size (n) | Approx. Operations |
|---|---|
| 10 rows | Parsing and planning fixed; execution scans about 10 rows |
| 100 rows | Parsing and planning same; execution scans about 100 rows |
| 1000 rows | Parsing and planning same; execution scans about 1000 rows |
Parsing and planning take about the same time no matter data size, but execution time grows with how many rows it reads.
Time Complexity: O(n)
This means the total time grows mostly with the number of rows the query reads during execution.
[X] Wrong: "Parsing and planning take longer as data grows."
[OK] Correct: Parsing and planning depend on query size, not data size, so they stay about the same even if data grows.
Knowing how query steps scale helps you explain database performance clearly. This skill shows you understand what happens behind the scenes when a query runs.
"What if the query uses an index to find rows? How would the time complexity change?"