Title - CASE SQL statement Tags - sql case programming
CASE statements create different outputs.
They are usually used in the SELECT statement.
It’s a way to use if-then logic in SQL.
Example:
We could condense movie ratings into three levels -
If the rating is above 8, then it is Fantastic. If the rating is above 6, then it is Poorly Received. Else, Avoid at All Costs.
Using this code -
SELECT name, CASE WHEN imdb_rating > 8 THEN ‘Fantastic’ WHEN imdb_rating >6 THEN ‘Poorly Received’ ELSE ‘Avoid at All Costs’ END AS ‘Review’ FROM movies;
Here -
WHEN tests a condition THEN gives us the string if the condition is true ELSE gives us the string if all conditions are false END signifies the end of the CASE statement and the END AS variant renames the column to ‘Review’ to shorten the column name and make the results readable without scrolling right.