Range types (int4range, daterange) in PostgreSQL - Time & Space Complexity
When working with range types like int4range or daterange in PostgreSQL, it's important to understand how the time to process queries grows as the data size increases.
We want to know how the number of operations changes when we search or filter using these range types.
Analyze the time complexity of this query using a range type filter.
SELECT *
FROM events
WHERE event_date && daterange('2024-01-01', '2024-12-31', '[]');
This query selects all rows where the event_date range overlaps with the year 2024.
Look for repeated checks or scans in the query.
- Primary operation: Checking each row's event_date range for overlap.
- How many times: Once per row in the events table.
As the number of rows grows, the database must check more ranges for overlap.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 overlap checks |
| 100 | 100 overlap checks |
| 1000 | 1000 overlap 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 linearly with the number of rows in the table.
[X] Wrong: "Using range types automatically makes queries run in constant time."
[OK] Correct: The database still needs to check each row unless an index is used, so the time grows with the number of rows.
Understanding how range queries scale helps you explain query performance clearly and shows you know how databases handle special data types.
What if we added a GiST index on the event_date column? How would the time complexity change?