Conditional Logic
10 Functions
Conditional logic allows your SQL queries to return different values based on specific conditions. It functions like "If-Then-Else" logic in programming, enabling you to categorize data, handle missing values, and perform complex business logic directly within your SELECT statements.
Table of Contents
CASE (Simple)
Compares an expression to a set of simple values to determine the result.
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
ELSE default_result
ENDTranslating numeric status codes into human-readable text.
SELECT status_code, CASE status_code WHEN 1 THEN 'Active' WHEN 0 THEN 'Inactive' ELSE 'Unknown' END AS status_labelFROM users;Simple CASE is cleaner when you are checking a single column against specific constants.
CASE (Searched)
Evaluates a set of Boolean expressions to determine the result. More flexible than Simple CASE.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
ENDCategorizing users into "Tiers" based on their XP ranges in XQLora.
SELECT username, xp, CASE WHEN xp >= 5000 THEN 'Legend' WHEN xp >= 1000 THEN 'Expert' ELSE 'Beginner' END AS rankFROM users;The order of WHEN clauses matters! The first condition that evaluates to TRUE is the one that gets executed.
COALESCE()
Returns the first non-null value from a list of arguments.
COALESCE(value1, value2, ..., value_n)Providing a fallback "Guest" name if a user hasn't set their display name.
SELECT COALESCE(display_name, username, 'Anonymous') FROM profiles;This is the most common way to handle NULL values in reports to prevent empty cells in your UI.
NULLIF()
Returns NULL if two arguments are equal; otherwise, it returns the first argument.
NULLIF(value1, value2)Preventing "Division by Zero" errors by turning a zero denominator into NULL.
SELECT total_sales / NULLIF(total_orders, 0) FROM stats;Since dividing by NULL results in NULL (not an error), this keeps your queries from crashing on bad data.
GREATEST()
Returns the largest value from a list of any number of expressions.
GREATEST(value1, value2, ...)Comparing multiple columns to find the most recent activity date.
SELECT GREATEST(last_login, last_quest_date, last_arena_date) FROM users;Unlike MAX(), which works across many rows, GREATEST() works across multiple columns in a single row.
LEAST()
Returns the smallest value from a list of any number of expressions.
LEAST(value1, value2, ...)Applying the lower of two possible discount rates.
SELECT LEAST(manual_discount, automatic_coupon) FROM checkout;Just like GREATEST(), this ignores NULL values unless all arguments are NULL.
IS DISTINCT FROM
A null-safe comparison operator that returns true if two values are different, even if one is NULL.
value1 IS DISTINCT FROM value2Detecting if a column value has changed, especially when switching from a value to NULL.
SELECT * FROM audit_logs WHERE old_value IS DISTINCT FROM new_value;Standard = returns NULL if compared to a NULL. This operator treats NULL as a comparable value.
IS NOT DISTINCT FROM
A null-safe comparison that returns true if two values are equal, treating two NULLs as "equal."
value1 IS NOT DISTINCT FROM value2Joining two tables where the join key might contain NULL values.
SELECT * FROM t1 JOIN t2 ON t1.id IS NOT DISTINCT FROM t2.id;Basically the opposite of IS DISTINCT FROM. Useful for joins matching NULLs.
FILTER (WHERE ...)
A PostgreSQL-specific conditional logic for aggregate functions.
AGG_FUNC(column) FILTER (WHERE condition)Calculating "Bronze" and "Silver" quest completions in a single query.
SELECT user_id, COUNT(*) FILTER (WHERE type = 'Bronze') AS bronze_count, COUNT(*) FILTER (WHERE type = 'Silver') AS silver_countFROM user_quests GROUP BY user_id;This is much more efficient and readable than using multiple CASE statements inside counts.
Logical IF (via CASE)
While PostgreSQL doesn't have a standalone IF() function (like MySQL), the logic is fully handled by CASE.
CASE WHEN condition THEN true_val ELSE false_val ENDSimple binary logic, like checking if a user is "Eligible" for a reward.
SELECT username, CASE WHEN xp > 100 THEN 'Eligible' ELSE 'Locked' END FROM users;PostgreSQL doesn't have IF() function like MySQL/Excel. Use CASE instead.