0
0
PostgreSQLquery~5 mins

IF-ELSIF-ELSE control flow in PostgreSQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: IF-ELSIF-ELSE control flow
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Checking conditions happens in a fixed sequence regardless of input size.

Input Size (n)Approx. Operations
104 checks max
1004 checks max
10004 checks max

Pattern observation: The number of checks stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the IF-ELSIF-ELSE does not grow with input size; it stays constant.

Common Mistake

[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.

Interview Connect

Understanding that IF-ELSIF-ELSE runs in constant time helps you explain how simple decision logic works efficiently in databases.

Self-Check

"What if we replaced IF-ELSIF-ELSE with a loop checking many conditions? How would the time complexity change?"