Ravindra BagaleCourses & study guides Track your progress

8. CASE WHEN: If-Then Logic in SQL

8.2 How to Write Simple CASE WHEN … THEN … ELSE

Why. One clear CASE pattern covers most label jobs.

What. CASE WHEN condition THEN value … ELSE value END

How. End with END. Alias the result column.

Steps

  1. Label Pune vs Other.
  2. Read WHEN top to bottom — first match wins.
  3. Always include ELSE when you can.

Examples

Example 1 · dataset: raja_coffee

SELECT order_id, city,
  CASE WHEN city = 'Pune' THEN 'Home city'
       ELSE 'Other city' END AS city_group
FROM orders
LIMIT 8;

Output

order_idcitycity_group
1001PuneHome city
1002MumbaiOther city
1003GoaOther city
1004PuneHome city
1005KolhapurOther city
1006PuneHome city
1007NashikOther city
1008SolapurOther city

Meaning. Each row gets a rule-based label.

Ravindra Bagale's Tip

Forgot END? SQLite throws a syntax error near SELECT — add END.