Almost every programming language has a way to represent "if, then, else", or conditional logic. In SQL, we represent this logic with the
CASE statement, as follows:
WHEN elevation < 500 THEN 'Low'
WHEN elevation BETWEEN 500 AND 1999 THEN 'Medium'
WHEN elevation >= 2000 THEN 'High'
END AS elevation_tier
GROUP BY 1;
In the above statement,
END is required to terminate the statement, but
ELSE is optional. If
ELSE is not included, the result will be
NULL. Also notice the shorthand method of referencing columns to use in
GROUP BY, so we don't have to rewrite the entire Case Statement.