CASE Expressions: Searched

Searched CASE expressions associate a list of alternative return values with a list of true/false conditions. They also allow you to implement an IS NULL test. For example:

SELECT u.name,
   CASE
      WHEN u.open_to_public = 'y' THEN 'Welcome!'
      WHEN u.open_to_public = 'n' THEN 'Go Away!'
      WHEN u.open_to_public IS NULL THEN 'Null!'
      ELSE 'Bad code!'
   END AS column_alias
FROM upfall u;

Null is returned when no condition is TRUE and no ELSE is specified. If multiple conditions are TRUE, the first-listed condition takes precedence.

Get SQL Pocket Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.