IF-ELSIF-ELSE control flow in PostgreSQL - Time & Space Complexity
When using IF-ELSIF-ELSE in PostgreSQL, we want to know how the time to run the code changes as the input grows.
We ask: Does checking conditions take more time if we have more data?
Analyze the time complexity of the following code snippet.
DO $$
DECLARE
score INTEGER := 75;
grade TEXT;
BEGIN
IF score >= 90 THEN
grade := 'A';
ELSIF score >= 80 THEN
grade := 'B';
ELSIF score >= 70 THEN
grade := 'C';
ELSE
grade := 'F';
END IF;
END $$;
This code assigns a grade based on the score using IF-ELSIF-ELSE control flow.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking conditions one by one in order.
- How many times: Each condition is checked at most once until one matches.
Checking conditions happens in a fixed sequence regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 4 checks max |
| 100 | 4 checks max |
| 1000 | 4 checks max |
Pattern observation: The number of checks stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run the IF-ELSIF-ELSE does not grow with input size; it stays constant.
[X] Wrong: "More data means more IF checks and slower code."
[OK] Correct: The IF-ELSIF-ELSE checks only a fixed number of conditions, not all data rows.
Understanding that IF-ELSIF-ELSE runs in constant time helps you explain how simple decision logic works efficiently in databases.
"What if we replaced IF-ELSIF-ELSE with a loop checking many conditions? How would the time complexity change?"