Back to DATA RETRIEVAL & FILTERING

CASE WHEN

Understand `CASE WHEN` for data manipulation

9 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.

Ready to continue?

Mark this lesson as complete when you're ready to proceed.

Key moments

  1. Introduction to CASEThe CASE statement adds if/else logic to a SELECT query.
  2. Basic CASE structureA simple CASE statement requires WHEN, THEN, and END keywords.
  3. Multiple WHEN conditionsMultiple WHEN clauses can be chained to categorize data into different groups.
  4. Aliasing and BETWEENThe BETWEEN operator defines inclusive ranges, and AS aliases the final CASE column.
  5. Conditional Salary RaiseA new scenario requires calculating different pay raises based on current salary thresholds.
  6. Calculation methodsThe raise calculation can be written using addition or simplified using multiplication.
  7. Handling edge casesCareful definition of conditions is necessary to avoid excluding boundary values like 50,000.
  8. Second CASE for BonusA second, independent CASE statement is used to calculate a bonus based on Department ID.
  9. Summary and Use CasesCASE statements are powerful for labeling, categorization, and conditional calculations.
PDF notes

Frequently asked questions

What happens if a value doesn't meet any WHEN condition?

The resulting column value for that row will be NULL. To prevent this, use an ELSE clause to define a default result.

Can I use an ELSE clause?

Yes, ELSE defines the default result if all preceding WHEN conditions are false. This is useful for catching all remaining cases.

Why did some employees not get a raise in the salary example?

The defined conditions (< 50000 and > 50000) excluded those making exactly 50,000. Conditions must be carefully defined to cover all boundaries.

Can I use CASE for calculations instead of just labeling?

Yes, the THEN clause can contain arithmetic operations, allowing you to calculate new values like salary increases or bonuses.