How do you write multiple conditions in an SQL CASE WHEN statement? | A1Lab@HumairaM to SQLEnglish • 2 days ago

How do you write multiple conditions in an SQL CASE WHEN statement?

message-square
0

To write multiple conditions in an SQL CASE WHEN expression, combine predicates using boolean logical operators (AND, OR, NOT) inside individual WHEN branches, or chain multiple WHEN branches so evaluation stops at the first matching condition. In SQL Server (T-SQL), use the searched CASE form (CASE WHEN <boolean_expr> THEN <result> … END) whenever conditions involve comparisons, ranges, NULLs, or multiple columns.

  1. Searched CASE with AND, OR, and Multiple WHEN Branches Searched CASE evaluates boolean expressions top-to-bottom and returns the THEN result of the first condition that evaluates to TRUE.

SQL SELECT order_id, customer_id, status, total_amount, CASE WHEN status = ‘CANCELLED’ THEN ‘Cancelled’ WHEN total_amount >= 1000.00 AND status = ‘COMPLETED’ THEN ‘High-Value Completed’ WHEN total_amount >= 250.00 OR status = ‘PRIORITY’ THEN ‘Standard Priority’ ELSE ‘Normal’ END AS order_tier FROM dbo.orders; Order matters: Once a WHEN condition is TRUE, later WHEN branches are skipped for that row. Place more specific or higher-priority conditions above broader ones.

Parentheses clarify precedence: Because AND binds tighter than OR, wrap mixed AND/OR predicates in parentheses—such as WHEN status = ‘COMPLETED’ AND (region = ‘North’ OR total_amount >= 500)—so evaluation order is explicit.

  1. Handling NULLs Explicitly in Conditions In SQL three-valued logic, col = NULL or col <> NULL evaluates to UNKNOWN (not TRUE), so NULL checks must use IS NULL or IS NOT NULL:

SQL SELECT customer_id, email, phone, CASE WHEN email IS NULL AND phone IS NULL THEN ‘No Contact Info’ WHEN email IS NULL THEN ‘Phone Only’ WHEN phone IS NULL THEN ‘Email Only’ ELSE ‘Complete Contact Info’ END AS contact_status FROM dbo.customers; 3. Searched CASE vs. Simple CASE Searched CASE (CASE WHEN cond1 AND cond2 THEN …): Supports full boolean logic (AND, OR, BETWEEN, IN, LIKE, IS NULL, cross-column comparisons). Recommended for multi-condition logic.

Simple CASE (CASE expr WHEN val1 THEN …): Compares a single expression against discrete values using equality (=). Avoid it when testing ranges, NULLs, or compound conditions.

  1. Operational Checklist Order WHEN branches from most specific to most general because the first TRUE match wins.

Group mixed AND and OR conditions with parentheses to avoid operator-precedence bugs.

Use IS NULL / IS NOT NULL rather than = NULL or <> NULL inside WHEN predicates.

Always include an ELSE branch (or account for NULL return) so unmatched rows do not produce unexpected NULLs, and keep returned THEN/ELSE data types compatible to avoid implicit conversion issues.