Bird
Raised Fist0
PostgreSQLquery~20 mins

CASE in PL/pgSQL in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
CASE Mastery in PL/pgSQL
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Output of CASE expression in PL/pgSQL function
What is the output of the following PL/pgSQL function when called with input value 15?
CREATE OR REPLACE FUNCTION test_case(val INTEGER) RETURNS TEXT AS $$
DECLARE
  result TEXT;
BEGIN
  result := CASE 
    WHEN val < 10 THEN 'Less than 10'
    WHEN val <= 20 THEN 'Between 10 and 20'
    ELSE 'Greater than 20'
  END;
  RETURN result;
END;
$$ LANGUAGE plpgsql;

SELECT test_case(15);
PostgreSQL
CREATE OR REPLACE FUNCTION test_case(val INTEGER) RETURNS TEXT AS $$
DECLARE
  result TEXT;
BEGIN
  result := CASE 
    WHEN val < 10 THEN 'Less than 10'
    WHEN val <= 20 THEN 'Between 10 and 20'
    ELSE 'Greater than 20'
  END;
  RETURN result;
END;
$$ LANGUAGE plpgsql;

SELECT test_case(15);
A'Greater than 20'
B'Less than 10'
C'Between 10 and 20'
DNULL
Attempts:
2 left
💡 Hint
Think about which WHEN condition matches the input value 15 first.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in CASE statement
Which option contains a syntax error in the CASE statement inside a PL/pgSQL block?
PostgreSQL
DECLARE
  grade CHAR := 'B';
  result TEXT;
BEGIN
  result := CASE grade
    WHEN 'A' THEN 'Excellent'
    WHEN 'B' THEN 'Good'
    ELSE 'Average'
  END;
END;
AMissing semicolon after END of CASE expression
BMissing ELSE clause in CASE expression
CNo syntax error; code is correct
DMissing END CASE keyword
Attempts:
2 left
💡 Hint
Check if the CASE expression is properly terminated with a semicolon.
optimization
advanced
2:00remaining
Optimizing multiple CASE statements in PL/pgSQL
You have multiple CASE statements checking the same variable in a PL/pgSQL function. Which approach is more efficient?
PostgreSQL
DECLARE
  status INTEGER := 2;
  message TEXT;
BEGIN
  -- Option 1: Multiple CASE statements
  IF status = 1 THEN
    message := 'Start';
  ELSIF status = 2 THEN
    message := 'Processing';
  ELSE
    message := 'Unknown';
  END IF;

  -- Option 2: Single CASE statement
  message := CASE status
    WHEN 1 THEN 'Start'
    WHEN 2 THEN 'Processing'
    ELSE 'Unknown'
  END;
END;
AOption 2 is more efficient because it uses a single CASE expression
BOption 1 is more efficient because IF statements are faster
CBoth options have the same efficiency
DOption 1 is more readable and thus preferred
Attempts:
2 left
💡 Hint
Consider how many times the variable is evaluated and how concise the code is.
🧠 Conceptual
advanced
2:00remaining
Understanding CASE with NULL values in PL/pgSQL
What will be the output of this PL/pgSQL snippet when input_value is NULL?
DECLARE
  input_value INTEGER := NULL;
  output TEXT;
BEGIN
  output := CASE input_value
    WHEN 1 THEN 'One'
    WHEN NULL THEN 'Null'
    ELSE 'Other'
  END;
  RETURN output;
END;
PostgreSQL
DECLARE
  input_value INTEGER := NULL;
  output TEXT;
BEGIN
  output := CASE input_value
    WHEN 1 THEN 'One'
    WHEN NULL THEN 'Null'
    ELSE 'Other'
  END;
  RETURN output;
END;
ARaises an error due to NULL comparison
B'Null'
C'One'
D'Other'
Attempts:
2 left
💡 Hint
Remember how NULL comparisons behave in SQL and PL/pgSQL CASE expressions.
🔧 Debug
expert
3:00remaining
Debugging unexpected CASE behavior in PL/pgSQL
A developer wrote this PL/pgSQL function but it always returns 'Unknown' regardless of input. What is the bug?
CREATE OR REPLACE FUNCTION check_status(code TEXT) RETURNS TEXT AS $$
DECLARE
  result TEXT;
BEGIN
  result := CASE code
    WHEN 'A' THEN 'Active'
    WHEN 'I' THEN 'Inactive'
    ELSE 'Unknown'
  END;
  RETURN result;
END;
$$ LANGUAGE plpgsql;

-- Called as: SELECT check_status('a');
PostgreSQL
CREATE OR REPLACE FUNCTION check_status(code TEXT) RETURNS TEXT AS $$
DECLARE
  result TEXT;
BEGIN
  result := CASE code
    WHEN 'A' THEN 'Active'
    WHEN 'I' THEN 'Inactive'
    ELSE 'Unknown'
  END;
  RETURN result;
END;
$$ LANGUAGE plpgsql;

-- Called as: SELECT check_status('a');
AVariable 'result' is not initialized before assignment
BCASE expression is case-sensitive, so 'a' does not match 'A'
CFunction lacks RETURNS clause
DMissing ELSE clause causes default to 'Unknown'
Attempts:
2 left
💡 Hint
Check how string comparisons work in CASE expressions.

Practice

(1/5)
1. What is the main purpose of using CASE in PL/pgSQL?
easy
A. To choose different actions based on conditions
B. To create loops that repeat actions
C. To define new tables in the database
D. To permanently store data in variables

Solution

  1. Step 1: Understand the role of CASE

    CASE is used to select one action from many based on conditions, like a traffic light deciding when to stop or go.
  2. Step 2: Compare with other options

    Loops repeat actions, table creation defines structure, and variables store data, none of which is the main role of CASE.
  3. Final Answer:

    To choose different actions based on conditions -> Option A
  4. Quick Check:

    CASE chooses actions based on conditions [OK]
Hint: CASE picks actions by conditions, not loops or storage [OK]
Common Mistakes:
  • Confusing CASE with loops
  • Thinking CASE creates tables
  • Assuming CASE stores data permanently
2. Which of the following is the correct way to end a CASE block in PL/pgSQL?
easy
A. END;
B. STOP;
C. FINISH CASE;
D. END CASE;

Solution

  1. Step 1: Recall PL/pgSQL syntax for CASE

    In PL/pgSQL, a CASE block must be closed with END CASE; to mark its end clearly.
  2. Step 2: Check other options

    END; ends blocks like functions, but CASE specifically needs END CASE;. FINISH CASE; and STOP; are invalid keywords.
  3. Final Answer:

    END CASE; -> Option D
  4. Quick Check:

    CASE ends with END CASE; [OK]
Hint: Always close CASE with END CASE; in PL/pgSQL [OK]
Common Mistakes:
  • Using END; alone to close CASE
  • Writing FINISH CASE; which is invalid
  • Using STOP; which is not a PL/pgSQL keyword
3. Consider this PL/pgSQL snippet:
DECLARE
  grade CHAR := 'B';
  result TEXT;
BEGIN
  CASE grade
    WHEN 'A' THEN result := 'Excellent';
    WHEN 'B' THEN result := 'Good';
    ELSE result := 'Average';
  END CASE;
  RETURN result;
END;

What will be the returned value?
medium
A. 'Good'
B. 'Average'
C. 'Excellent'
D. NULL

Solution

  1. Step 1: Identify the value of grade

    The variable grade is set to 'B'.
  2. Step 2: Match grade in CASE

    CASE checks 'B', matches the second WHEN clause, so result becomes 'Good'.
  3. Final Answer:

    'Good' -> Option A
  4. Quick Check:

    grade 'B' returns 'Good' [OK]
Hint: Match CASE value to WHEN clause for output [OK]
Common Mistakes:
  • Choosing ELSE when a WHEN matches
  • Confusing variable assignment inside CASE
  • Assuming NULL if no ELSE present
4. Identify the error in this PL/pgSQL CASE block:
DECLARE
  score INT := 85;
  grade TEXT;
BEGIN
  CASE
    WHEN score >= 90 THEN grade := 'A';
    WHEN score >= 80 THEN grade := 'B';
    ELSE grade := 'C';
  END;
  RETURN grade;
END;
medium
A. Incorrect variable declaration
B. Invalid comparison operators
C. Missing END CASE; to close CASE block
D. No ELSE clause present

Solution

  1. Step 1: Check CASE block ending

    The CASE block is closed with END; but PL/pgSQL requires END CASE; to close CASE.
  2. Step 2: Verify other parts

    Variable declarations and comparisons are correct, and ELSE clause is present.
  3. Final Answer:

    Missing END CASE; to close CASE block -> Option C
  4. Quick Check:

    CASE must end with END CASE; [OK]
Hint: Close CASE with END CASE;, not just END; [OK]
Common Mistakes:
  • Using END; instead of END CASE;
  • Thinking ELSE is optional here
  • Misreading comparison operators
5. You want to write a PL/pgSQL function that returns 'Pass' if a student's score is 50 or more, 'Fail' if below 50, and 'Invalid' if the score is NULL. Which CASE structure correctly implements this?
hard
A.
CASE score
  WHEN NULL THEN RETURN 'Invalid';
  WHEN >= 50 THEN RETURN 'Pass';
  ELSE RETURN 'Fail';
END CASE;
B.
CASE
  WHEN score IS NULL THEN RETURN 'Invalid';
  WHEN score >= 50 THEN RETURN 'Pass';
  ELSE RETURN 'Fail';
END CASE;
C.
CASE
  WHEN score >= 50 THEN RETURN 'Pass';
  WHEN score IS NULL THEN RETURN 'Fail';
  ELSE RETURN 'Invalid';
END CASE;
D.
CASE score
  WHEN score >= 50 THEN RETURN 'Pass';
  WHEN score < 50 THEN RETURN 'Fail';
  ELSE RETURN 'Invalid';
END CASE;

Solution

  1. Step 1: Handle NULL explicitly

    Since NULL cannot be matched by simple WHEN, use WHEN score IS NULL to check NULL values.
  2. Step 2: Order conditions correctly

    Check NULL first, then score >= 50 for 'Pass', else 'Fail'. This matches
    CASE
      WHEN score IS NULL THEN RETURN 'Invalid';
      WHEN score >= 50 THEN RETURN 'Pass';
      ELSE RETURN 'Fail';
    END CASE;
    .
  3. Final Answer:

    CASE with WHEN score IS NULL, then score >= 50, else Fail -> Option B
  4. Quick Check:

    Use IS NULL to check NULL in CASE [OK]
Hint: Use WHEN score IS NULL to test NULL in CASE [OK]
Common Mistakes:
  • Trying to match NULL with WHEN NULL
  • Using CASE score with conditions inside WHEN
  • Not checking NULL before other conditions