GREATEST and LEAST functions in PostgreSQL - Time & Space Complexity
We want to understand how the time it takes to find the greatest or least value changes as we give more values to compare.
How does the work grow when using GREATEST or LEAST with more inputs?
Analyze the time complexity of the following code snippet.
SELECT GREATEST(score1, score2, score3, score4, score5) AS max_score,
LEAST(score1, score2, score3, score4, score5) AS min_score
FROM player_scores;
This code finds the highest and lowest scores among five columns for each row in the table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing each value to find the greatest and least.
- How many times: Each row compares all given values once.
As you add more values to compare, the number of comparisons grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 4 comparisons |
| 10 | 9 comparisons |
| 100 | 99 comparisons |
Pattern observation: The number of comparisons increases directly with the number of values.
Time Complexity: O(n)
This means the time to find the greatest or least value grows linearly as you add more values to compare.
[X] Wrong: "GREATEST and LEAST instantly find the answer no matter how many values there are."
[OK] Correct: The functions must check each value to be sure which is largest or smallest, so more values mean more work.
Understanding how these functions scale helps you explain performance when working with many columns or values, showing you know how database operations grow with input size.
"What if we used GREATEST and LEAST on values stored in an array instead of separate columns? How would the time complexity change?"