What is PostgreSQL - Complexity Analysis
We want to understand how the time it takes to work with PostgreSQL grows as we handle more data or more complex queries.
How does PostgreSQL manage time when running commands on bigger data sets?
Analyze the time complexity of a simple SELECT query in PostgreSQL.
SELECT * FROM employees WHERE department_id = 5;
This query fetches all employees who belong to department number 5.
Look for repeated steps in the query process.
- Primary operation: Scanning rows in the employees table to find matches.
- How many times: Once for each row in the table, unless an index is used.
As the number of employees grows, the time to find those in department 5 changes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 row checks |
| 100 | 100 row checks |
| 1000 | 1000 row checks |
Pattern observation: The number of checks grows directly with the number of rows.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the table gets bigger.
[X] Wrong: "The query time stays the same no matter how big the table is."
[OK] Correct: Without special help like indexes, the database must check each row, so bigger tables take more time.
Knowing how query time grows helps you explain how databases handle data efficiently, a useful skill in many jobs.
"What if we added an index on department_id? How would the time complexity change?"