CASE Expression

Advanced SQLConditionalFree Lesson

Advertisement

The CASE Expression

Add conditional logic to your SQL queries with the CASE expression.

💡 CASE Expression are essential tools for handling conditional logic and NULL values in SQL.

CASE Syntax

-- Simple CASE (exact match)
CASE expression
    WHEN value1 THEN result1
    WHEN value2 THEN result2
    ELSE default_result
END

-- Searched CASE (conditions) 
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ELSE default_result
END

Example

SELECT
    first_name,
    salary,
    CASE
        WHEN salary >= 80000 THEN 'High'
        WHEN salary >= 60000 THEN 'Medium'
        ELSE 'Low'
    END AS salary_level,
    ''
FROM employees;

✅ Key Takeaways

  1. CASE adds if-then-else logic to SQL queries
  2. CASE can be used in SELECT, WHERE, ORDER BY, and UPDATE
  3. CASE has two forms: simple (exact match) and searched (conditions)
  4. Always include an ELSE clause in CASE to handle unexpected values
  5. CASE expressions can be nested for complex logic

Advertisement

Need Expert SQL Help?

Get personalized SQL training or database consulting.

Advertisement