Explain Codes LogoExplain Codes Logo

How do I perform an IF...THEN in an SQL SELECT?

sql
conditional-statements
sql-syntax
best-practices
Alex KataevbyAlex Kataev·Feb 13, 2025
TLDR

CASE statement, the knight in shining armor, saves the day in our SQL SELECT queries with conditional logic:

SELECT CASE WHEN condition THEN 'truthy' ELSE 'falsy' END as Alias FROM TableName;

Our champion CASE creates a new column displaying results 'truthy' or 'falsy' based on the initiating condition.

Diving into the depths of conditions

SQL syntax allows for nested CASE conditions, ideal for weaving through complex logical scenarios:

SELECT CASE WHEN first_cond THEN 'first_case' WHEN second_cond THEN CASE WHEN sub_cond THEN 'nested_case' ELSE 'nested_else' END ELSE 'first_else' END as Alias FROM TableName; -- Nested case statements: It's cases all the way down 🌌

SQL Server 2012+ provides a more succinct alternative: IIF. It's like the younger, cooler sibling of CASE:

SELECT IIF(condition, 'true_result', 'false_result') as Alias FROM TableName; -- IIF only it was this simple everywhere! 🔮

Conditional aggregation - What's your count?

The CASE statement shines when it's used within aggregated functions:

SELECT SUM(CASE WHEN condition THEN 1 ELSE 0 END) as ConditionalSum FROM TableName; -- Take a walk down memory SUM lane 💫

This SQL quirk lets you tally up the records fulfilling specific conditions.

SQL syntax: Where does CASE come in?

The positioning of CASE is crucial within the SQL syntax scheme, nestling between SELECT and FROM:

SELECT column1, column2, CASE WHEN condition THEN 'Yes' ELSE 'No' END as Alias FROM TableName; -- The CASE of the strategic positioning 🕵️‍♀️

Adding an alias to the CASE statement makes your code a peasier read by distinctly naming the result of the condition.

Playing with data types

Although CASE inherently returns integer type, specific scenarios might require a type conversion, handled by CAST:

SELECT CAST(CASE WHEN condition THEN 1 ELSE 0 END AS bit) as ConditionalBit FROM TableName; -- I CASE you were unsure about type handling...

With integers, you can go ahead and skip the CAST for more concise SQL:

SELECT (CASE WHEN condition THEN 1 ELSE 0 END) as Alias FROM TableName; -- CAST away, Wilson! 🏐

Compatibility and cross-breeding

The CASE statement is universally compatible across different SQL platforms, making it the preferred choice for cross-compatibility. And in those special scenarios where you need to alter the entire structure of the query, keep an eye out for procedural IF.

Tackling multiple outcomes

CASE can efficiently handle multi-outcome scenarios with layered condition checks in your SELECT clause:

SELECT column1, column2, CASE WHEN condition1 THEN 'Outcome1' WHEN condition2 THEN 'Outcome2' ELSE 'DefaultOutcome' END as Alias FROM TableName ORDER BY CASE WHEN sortCondition THEN 1 ELSE 2 END; -- Your CASE will be ORDERed...by number! 🧾

Seal off the CASE statement with the END keyword, following SQL's best practices.

Handling text values and platform compatibility

CASE statements aren't just binary logic dominators; they also handle textual descriptors:

SELECT CASE WHEN Gender = 'M' THEN 'Male' WHEN Gender = 'F' THEN 'Female' ELSE 'Other' END as GenderDescriptor FROM Persons; -- Conditional genders: Not as complex as real life! 🚹🚺

Given the support for CASE across SQL Server, PostgreSQL, MySQL, Oracle, etc., your SQL skills are universally applicable.

Streamlining complex conditions

Transforming convoluted if-then-else constructs into easy-to-read CASE structures elevates the readability and efficiency of your SQL queries. Always aim for simplicity and directness, even with CASE.

Watch out for the traps!

With procedural IF in SQL Server, beware of the parameter sniffing issue that can lead to suboptimal plan choices by the query optimizer due to parameter values at compile time. Overcome this issue with option recompile, variable assignments, or query hints.