Master CASE WHEN for conditional logic, handle NULLs gracefully with COALESCE, manipulate strings and dates, and combine result sets with UNION and friends. This lesson uses SQLite-flavored functions and emphasizes how result grain changes when you group or stack results.
Use CASE WHEN to add conditional logic directly in your SQL query.
SELECT name, price, CASE WHEN price < 20 THEN 'Budget' WHEN price < 50 THEN 'Mid-Range' WHEN price < 100 THEN 'Premium' ELSE 'Luxury' END AS price_tier FROM products ORDER BY price;CASE WHEN evaluates conditions in order and returns the value for the first TRUE condition. It works like an if/else-if/else chain. The ELSE clause catches anything that didn't match earlier conditions. END closes the CASE block. This lets you create new categories, labels, or calculated values on the fly without modifying your data.
Every product now has a price_tier column: Budget, Mid-Range, Premium, or Luxury. Products are sorted by price so you can see the tier boundaries clearly.