Conditional Aggregates


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:

SELECT CASE WHEN elevation < 500 THEN 'Low' WHEN elevation BETWEEN 500 AND 1999 THEN 'Medium' WHEN elevation >= 2000 THEN 'High' ELSE 'Unknown' END AS elevation_tier , COUNT(*) FROM airports 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.

Community Forums
Get help and ask questions in the Codecademy Forums
Report a Bug
If you see a bug or any other issue with this page, please report it here.