-
Notifications
You must be signed in to change notification settings - Fork 0
/
CASE Statement
47 lines (38 loc) · 1.37 KB
/
CASE Statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
A CASE statement allows us to create different outputs (usually in the SELECT statement).
It is SQL’s way of handling if-then logic.
Example:
Suppose we want to condense the ratings in movies to 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.
SELECT name,
CASE
WHEN imdb_rating > 8 THEN 'Fantastic'
WHEN imdb_rating > 6 THEN 'Poorly Received'
ELSE 'Avoid at All Costs'
END
FROM movies;
Each WHEN tests a condition and the following THEN gives us the string if the condition is true.
The ELSE gives us the string if all the above conditions are false.
The CASE statement must end with END.
In the result, you have to scroll right because the column name is very long. To shorten it, we can rename the column to ‘Review’ using AS:
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;
Example:
SELECT name,
CASE
WHEN genre = 'romance' THEN 'Chill'
WHEN genre = 'comedy' THEN 'Chill'
ELSE 'Intense'
END AS 'Mood'
FROM movies;
Select the name column and use a CASE statement to create the second column that is:
‘Chill’ if genre = 'romance'
‘Chill’ if genre = 'comedy'
‘Intense’ in all other cases
Optional: Rename the whole CASE statement to ‘Mood’ using AS.