PostgreSQL CASE Statement Explained
In PostgreSQL, the CASE expression is used in a SELECT statement to return different values based on conditions. The syntax is as follows:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
Conditions such as condition1, condition2, and results such as result1, result2 are expressions used to determine the value returned when a condition is met. The default_result is the value returned if none of the conditions are met.
For example, the following example demonstrates a simple usage of a CASE statement:
SELECT
name,
CASE
WHEN age < 18 THEN 'Child'
WHEN age >= 18 AND age < 65 THEN 'Adult'
ELSE 'Senior'
END AS age_group
FROM users;
In this example, different age groups are returned based on the user’s age. If the age is less than 18, ‘Child’ is returned. If the age is between 18 and 65, ‘Adult’ is returned, otherwise ‘Senior’ is returned.