Case statements
Often, we want to display data based on some sort of condition. In these situations, a case statement can be used to display data relative to a condition. The case statement syntax is shown here:
CASE WHEN [condition 1] THEN [result1] WHEN [condition 2] THEN [result2] … [ELSE] [resultn] END
For example, suppose that you had a table of users named userTable
, which contained users of varying ages. If a user is age 18 or older, you want to show them as an adult. If a user is younger than age 18, you want to show them as a youth. To achieve this, you can use a case statement, like so:
SELECT CASE WHEN age >= 18 THEN ‘adult’ ELSE ‘youth’ END AS isadult FROM user;
The next exercise demonstrates a practical example of case statements.