SQL and databases

Stage 2 · Lesson 6 of 8

CASE expressions

Querying one table

A is if-then-else inside SQL. It checks its conditions in order and returns the value for the first one that is true. If none is true, it returns the ELSE value, or NULL if there is no ELSE.

Use it to turn codes into readable labels, sort prices into bands, or order rows in a custom . It works in SELECT, WHERE and , and inside aggregates such as SUM. That last use becomes in a later stage.

CASE is standard SQL and works the same on all three databases, unlike shortcuts such as IF() in MySQL or IIF() in .

Common trapoverlapping conditions in the wrong order, such as checking price < 50 before price < 10, so the second branch never matches.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

  • CoursePaid
    Grokking SQL for Tech Interviews

    Design Gurus · Intermediate · Subscription

    The basics, order of execution and functions chapters, each followed by graded problems

  • CourseFree
    SQLBolt

    SQLBolt · Beginner

    Free: Lessons 1 to 4, 8, 9 and 12 cover SELECT, filtering, sorting, NULLs, expressions and query order

Practise

Keep handy

  • The SELECT statement page and the string and date function chapters

  • Its SQL pages give quick examples and note where MySQL and SQL Server syntax differ

Also worth your time

Mark this stage as not done?