EXTRACT function for date parts in PostgreSQL - Time & Space Complexity
We want to understand how the time it takes to get parts of a date grows as we work with more data.
How does the EXTRACT function behave when used on many rows?
Analyze the time complexity of the following code snippet.
SELECT EXTRACT(YEAR FROM order_date) AS order_year
FROM orders;
This code gets the year part from the order_date column for every row in the orders table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Extracting the year from each date in the orders table.
- How many times: Once for every row in the orders table.
Each row requires one extraction operation, so the total work grows as the number of rows grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 extractions |
| 100 | 100 extractions |
| 1000 | 1000 extractions |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles work.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the number of rows increases.
[X] Wrong: "EXTRACT runs in constant time no matter how many rows there are."
[OK] Correct: EXTRACT runs once per row, so more rows mean more work and more time.
Understanding how functions like EXTRACT scale helps you write efficient queries and explain their performance clearly.
"What if we added a WHERE clause to filter rows before extracting? How would the time complexity change?"