…
…
SQL and Database Fundamentals · Lesson 8 / 41 · CASE and the order a query runs
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The dean's office wants a column next to each student on the graduation list that says "High honors", "Honors", "Normal" or "No GPA". The registrar's office also wants each course record to say "Passed", "Failed" or "Awaiting final". These labels are not in the table; they have to be produced inside the query, row by row, by looking at the rule.
So far you have either returned columns as they are or calculated with them: in lesson 3 you calculated the score with 0.4 * midterm + 0.6 * final_exam, and in lesson 7 you wrote a text into a blank cell with COALESCE. The dean's request is different. For a student with a GPA of 3.65, you will not write a number but a decision: "High honors". The rule for this decision is not a single condition but several thresholds checked in order: 3.5 and above, 3.0 and above, students whose GPA was never entered, and everyone else. You could filter the 120 students with four separate WHERE queries and join the lists by hand; but the dean wants one list, with each row's own label next to it. In this lesson you will learn the tool for this, the CASE expression.
In this lesson you will:
The target output looks like this: in the list, each student has a number, a name, a GPA and, on the far right, a new status column. One of the first rows is 202303001 | Anika | 3.65 | High honors, and another is 202604001 | Felix | NULL | No GPA. This column is not in the table; the query produces it again for each row.
CASE is SQL's "if ... then" structure. It tries the conditions in order and returns the value next to the first true condition. Its general form is:
OutputCASE
WHEN condition1 THEN value1
WHEN condition2 THEN value2
ELSE default
ENDEach WHEN asks a question, and THEN says which value to return if the answer is "yes". If no question gets a "yes", ELSE speaks. At the very end, END closes the expression. In place of a condition you can write anything you know from lesson 4: >=, <, =, AND, OR, IS NULL.
The most important point: CASE is an expression, which means it produces a single value for each row. Just as 0.4 * midterm + 0.6 * final_exam produces a number for each row, CASE produces a label for each row. So it can be written anywhere a column can be written. The most common place is the SELECT list: it produces a new label column, and you give it a name at the end with AS. If you do not give it a name, the column header becomes case and nobody reading the report will understand what it is.
Example 1: Honors status. Let's turn the dean's rule directly into a query:
SELECT student_no, first_name, gpa, CASE WHEN gpa >= 3.5 THEN 'High honors' WHEN gpa >= 3.0 THEN 'Honors' WHEN gpa IS NULL THEN 'No GPA' ELSE 'Normal' END AS status FROM student;
Result (four of the 120 rows):
| student_no | first_name | gpa | status |
|---|---|---|---|
| 202303001 | Anika | 3.65 | High honors |
| 202405001 | Anika | 3.88 | High honors |
| 202604001 | Felix | NULL | No GPA |
| 202304001 | Isabella | 2.57 | Normal |
Let's follow the rows one by one. Anika's 3.65 says "yes" to the first question, the official stops: "High honors". Isabella's 2.57 says "no" to the first two questions; the third question asks "is the GPA blank?", and that is also "no"; only ELSE is left: "Normal". Felix's GPA is blank; we will follow his journey in detail in section 4. Now arrange the lines of the same CASE yourself.
Arrange the CASE lines so that everyone who deserves the High honors label gets it.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Instead of writing a big CASE in one go, it is safer to grow the report step by step: at each step you run the query, see that the result is what you expected, and then add a part. The dean's office first wants to see only fourth-year students, that is, those who graduate this year.
(a) The list without labels. SELECT first_name, last_name, gpa FROM student WHERE year = 4; returns 21 rows. There is no label yet; you are only checking who is on the list.
(b) A label with two branches. First add the simplest rule: CASE WHEN gpa >= 3.5 THEN 'High honors' ELSE 'Normal' END AS status. When you run it, you see "High honors" next to Camila Osei (3.88) and "Normal" next to Rosa Haddad (2.12). The logic works; but Emeka Okafor, who has 3.41, also looks "Normal", because there is no "Honors" branch yet.
(c) All branches and sorting. Add the "Honors" branch, a separate branch for blank GPAs and the sorting you know from lesson 6. In the cell below, the final version for all students is ready: the NULL branch comes first, the list is sorted by GPA from high to low, blanks last, first 8 rows. Run it as it is first, then try two tasks:
1. The advising office also wants to see those whose GPA is below 2.0: add a WHEN gpa < 2.0 THEN 'Warning' branch right before ELSE. Change DESC to ASC to see the students with a warning.
2. The dean's office is thinking of lowering the "High honors" threshold to 3.25: change 3.5 to 3.25 and see which students' labels change.
Try it now· not graded; doesn't affect progress
In the first task, the place of the new branch matters: if you write it after ELSE, the query raises an error, because ELSE is always last. In the second task you changed only one number and the meaning of the report changed. Because the business rule is written inside the query, when the rule changes there is only a single line to change.
The most important rule of CASE is this: conditions are tried from top to bottom and the value of the first true condition is returned; the following conditions are never looked at. CASE does not search for the "best fit" branch, and it does not evaluate all conditions and pick the best. It stops at the first "yes".
This rule sets a trap in classifications with thresholds. A GPA of 3.8 satisfies both the >= 3.5 and the >= 3.0 condition. Whichever condition is written first wins. If you write the conditions in reverse, that is, >= 3.0 first, all students at 3.0 and above stop at the first branch and get "Honors". In the case there are 27 students with a GPA of 3.0 and above; in the reverse order all 27 get the label "Honors" and the label "High honors" never appears in the list. PostgreSQL does not raise an error, because the query is correct in terms of syntax; what is wrong is the logic. The rule is simple: with thresholds, the narrowest condition is written first. "3.5 and above" is a narrower set than "3.0 and above", so it comes first.
What does this query return?
SELECT CASE WHEN 3.8 >= 3.0 THEN 'Honors' WHEN 3.8 >= 3.5 THEN 'High honors' ELSE 'Normal' END;
CASE has two separate relationships with blank values, and both are often confused.
The first: if ELSE is not written, the result is NULL. If no condition is true and there is no ELSE, CASE does not return "the last label" or "an empty string"; it returns NULL. Sometimes this is what you want, but most of the time it is an oversight.
Example 2: An honors list without ELSE. Let's write only two branches for fourth-year students and forget ELSE:
SELECT first_name, gpa, CASE WHEN gpa >= 3.5 THEN 'High honors' WHEN gpa >= 3.0 THEN 'Honors' END AS status FROM student WHERE year = 4 ORDER BY gpa;
Result (first 2 of 21 rows):
| first_name | gpa | status |
|---|---|---|
| Adaeze | 0.14 | NULL |
| Priya | 0.93 | NULL |
12 of the 21 students did not match either condition, so their status cells stayed blank; Rosa (2.12) and Aisha (1.46) are among them. If you see unexpected blank cells in a list, the first place to look is ELSE.
The second: a row whose value is NULL falls into ELSE. As you saw in lesson 7, a comparison with NULL is neither true nor false but unknown. gpa >= 3.5 does not say "yes" for a blank GPA. Because CASE stops only at "yes", this row passes every branch and finally reaches ELSE. So a NULL row does not raise an error and does not disappear either; it quietly gets the label in ELSE. If you want blanks to have their own label, you must write an explicit branch: WHEN gpa IS NULL THEN 'No GPA'.
Example 3: Weather readings (outside the case). The same rule is valid in every table. In the measurement table of a weather app there is this morning's temperature for six cities; the station in Seoul is broken and no reading came in:
| city | temperature |
|---|---|
| Oslo | -6 |
| Toronto | 4 |
| Port Alder | 11 |
| Lisbon | 17 |
| Nairobi | 22 |
| Seoul | NULL |
Let's split the temperature into three labels; let's write a separate branch for the blank reading:
SELECT city, temperature, CASE WHEN temperature IS NULL THEN 'No reading' WHEN temperature < 5 THEN 'Cold' WHEN temperature < 18 THEN 'Mild' ELSE 'Hot' END AS weather FROM measurement;
| city | temperature | weather |
|---|---|---|
| Oslo | -6 | Cold |
| Toronto | 4 | Cold |
| Port Alder | 11 | Mild |
| Lisbon | 17 | Mild |
| Nairobi | 22 | Hot |
| Seoul | NULL | No reading |
(6 rows)
Here the thresholds are written with <, so we go from small to large. The "narrowest first" rule still applies: the set "less than 5" is inside the set "less than 18", so it comes first. Another developer of the same app wrote the CASE in a hurry: first temperature < 18 THEN 'Mild', then temperature < 5 THEN 'Cold', ELSE 'Hot', and no NULL branch. In this version Oslo and Toronto also look "Mild", because -6 and 4 stop at the first branch. And what about Seoul?
In this CASE without a NULL branch, which label does Seoul (temperature is NULL) get?
CASE WHEN temperature < 18 THEN 'Mild' WHEN temperature < 5 THEN 'Cold' ELSE 'Hot' END
Now use the two rules together. A record in the registrar's database has a midterm of 80 and a final that has not been entered yet (NULL). What does each CASE below return for this record?
For the record with midterm = 80 and final_exam = NULL, what does each CASE return?
For each row, pick its match from the list, then check.
CASE WHEN final_exam >= 50 THEN 'Passed' ELSE 'Failed' ENDCASE WHEN final_exam >= 50 THEN 'Passed' ENDCASE WHEN final_exam IS NULL THEN 'Pending' WHEN final_exam >= 50 THEN 'Passed' ELSE 'Failed' ENDCASE WHEN midterm >= 50 THEN 'Midterm good' ELSE 'Midterm weak' ENDIf you are only checking whether a single column is equal to certain values, there is a shorter form. You write the column once right after CASE, and in each WHEN you put only the value. This is called a simple CASE; what you have written so far is a searched CASE.
Example 4: Year label.
SELECT first_name, year, CASE year WHEN 1 THEN 'First' WHEN 2 THEN 'Second' ELSE 'Upper' END AS label FROM student;
Result (two of the 120 rows):
| first_name | year | label |
|---|---|---|
| Anika | 4 | Upper |
| Felix | 1 | First |
CASE year WHEN 1 is really a shortcut for CASE WHEN year = 1. The short form checks only equality: you cannot write a comparison like >= or IS NULL. There is a trap here. CASE gpa WHEN NULL THEN 'No GPA' ... looks like it catches the blanks but it never matches. Behind the scenes the short form asks the question gpa = NULL, and as you know from lesson 7, this comparison is never true for any row. For blanks, always use a searched CASE and IS NULL.
All values of a column must be of the same type: either all numbers or all text. Because CASE also produces a column, the values returned by all its branches must be of the same type. Suppose you wanted to write "none" for students without a GPA and show the GPA as it is for the others:
SELECT first_name, CASE WHEN gpa IS NULL THEN 'none' ELSE gpa END AS status FROM student;
OutputERROR: invalid input syntax for type numeric: "none"PostgreSQL decided the type of the column based on one of the branches, here gpa, which is a number, and tried to convert the text "none" to a number; when it could not, it stopped the query. The message says "invalid input for type numeric (number): none". The solution is not to mix a number and a label in the same column: a label column should be text from start to end (as in Example 1), and the GPA should stay in its own column. You will see how to convert a number to text together with data types in lesson 25.
Since CASE produces a value, it can be used not only in SELECT but also in ORDER BY. The faculty wants the instructor list sorted by title, but not alphabetically; by academic seniority: first professors, then associate professors, then assistant professors, and last the others. ORDER BY title follows the alphabet and puts "Associate Professor" before "Professor". The solution: write a CASE that gives each title a rank number and sort by that number.
Example 5: Instructors by seniority. Those with the same title are sorted by last name among themselves:
SELECT first_name, last_name, title FROM instructor ORDER BY CASE title WHEN 'Professor' THEN 1 WHEN 'Associate Professor' THEN 2 WHEN 'Assistant Professor' THEN 3 ELSE 4 END, last_name;
Result (first 5 of 20 rows):
| first_name | last_name | title |
|---|---|---|
| Clara | Abara | Professor |
| Tessa | Fernández | Professor |
| Fatima | Müller | Professor |
| Olivia | Osei | Professor |
| Diego | Costa | Associate Professor |
The four professors are at the top, followed by the associate professors. At the end of the list there are six lecturers who fall into ELSE. The CASE here was written in the short form, because we are checking whether the titles are equal. The query is ready in the cell below. Task: for the new term, the lecturers are wanted at the top of the list. Do this by adding a branch to the CASE or changing the numbers.
Try it now· not graded; doesn't affect progress
One way is to add the branch WHEN 'Lecturer' THEN 0: because 0 is smaller than 1, the lecturers move to the top. Making ELSE 0 gives the same result, but if a new title is added to the list in the future, it will also move to the top. Writing an explicit branch states your intent more clearly.
Let's go back to the registrar's request. The score of each record is 40% midterm and 60% final; 50 and above passes. In this term's records the final has not been entered yet. Writing "Failed" for these records would be both wrong and unfair: the student has not even taken the exam. The registrar's office wants three labels.
Example 6: Pass status.
SELECT id, midterm, final_exam, 0.4 * midterm + 0.6 * final_exam AS score, CASE WHEN final_exam IS NULL THEN 'Awaiting final' WHEN 0.4 * midterm + 0.6 * final_exam >= 50 THEN 'Passed' ELSE 'Failed' END AS result FROM enrollment ORDER BY id;
Result (first 6 of 781 rows):
| id | midterm | final_exam | score | result |
|---|---|---|---|---|
| 1 | 96 | 73 | 82.2 | Passed |
| 2 | 90 | 87 | 88.2 | Passed |
| 3 | 91 | 100 | 96.4 | Passed |
| 4 | 92 | 96 | 94.4 | Passed |
| 5 | 72 | NULL | NULL | Awaiting final |
| 6 | 99 | NULL | NULL | Awaiting final |
Of the 781 records, 462 got "Passed", 9 got "Failed" and 310 got "Awaiting final". In record 5 the blank final made the score blank too: as you saw in lesson 7, NULL spreads into calculations. In the CASE we had to write the score calculation again, because the score alias given in the same SELECT cannot be used inside the CASE; you will see why in the next lesson.
If we move the WHEN final_exam IS NULL branch of the CASE in Example 6 to the bottom, right above ELSE, what do the records without a final get?
CASE WHEN 0.4 * midterm + 0.6 * final_exam >= 50 THEN 'Passed' WHEN final_exam IS NULL THEN 'Awaiting final' ELSE 'Failed' END
Finally, look again at the COALESCE from lesson 7. COALESCE(room, 'Online') is really a small CASE: CASE WHEN room IS NULL THEN 'Online' ELSE room END. To fill a single blank, COALESCE is shorter; when you need several conditions, thresholds or labels, you write CASE. CASE can also be written inside WHERE, but for filtering AND and OR are usually more readable. Another strong use of CASE is counting the rows that meet a condition; you will see that in lesson 11 together with aggregate functions.
Two of the sections opened this term have no room; they are held online. Let's produce the same label in two ways; let the list contain two sections with a room and two without:
SELECT id, capacity, CASE WHEN room IS NULL THEN 'Online' ELSE room END AS place, COALESCE(room, 'Online') AS place_short FROM course_offering WHERE term_id = 3 AND (room IS NULL OR id <= 5) ORDER BY id;
| id | capacity | place | place_short |
|---|---|---|---|
| 2 | 40 | C-417 | C-417 |
| 5 | 50 | C-116 | C-116 |
Writing the conditions in the wrong order. If the wide condition comes first, the narrow condition never gets its turn:
OutputCASE
WHEN gpa >= 3.0 THEN 'Honors' -- 3.8 stops here too
WHEN gpa >= 3.5 THEN 'High honors' -- never runs
ELSE 'Normal'
ENDPostgreSQL does not raise an error; the label "High honors" simply never appears in the list, and all 27 students with a GPA of 3.0 and above become "Honors". You can catch this mistake only by looking at the result: a label that never appears, or appears more often than expected, is a warning sign. With threshold conditions, start with the narrowest condition, and after writing the CASE, follow at least one boundary value (for example exactly 3.5) in your head from top to bottom.
CASE WHEN condition THEN value ... ELSE default END produces a single value for each row; it is used as a label column named with AS in SELECT, and as an invisible rank number in ORDER BY. All branches must return values of the same type.WHEN column IS NULL branch is written for blanks (CASE column WHEN NULL never matches).Next lesson: You will read the execution order of the clauses and error messages; you will see there why an alias does not work in WHERE.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| 18 |
| 40 |
| Online |
| Online |
| 31 | 30 | Online | Online |
(4 rows)
The two columns are the same in every row. Note: both branches of the CASE here return text ('Online' and room, which is a text type); that is why there is no error.
A music app, Earbud, offers ad-free listening to premium members and listening with ads to free members. The plan column in the listener table takes only two values; because we are checking equality, the short form is suitable:
SELECT id, nickname, plan, CASE plan WHEN 'premium' THEN 'Ad-free' ELSE 'With ads' END AS listening_type FROM listener ORDER BY id LIMIT 5;
| id | nickname | plan | listening_type |
|---|---|---|---|
| 1 | night_owl | premium | Ad-free |
| 2 | pixel_ada | free | With ads |
| 3 | purple_earbuds | premium | Ad-free |
| 4 | rustic42 | free | With ads |
| 5 | bass_guitar | free | With ads |
(5 rows)
ELSE is a deliberate choice here: "everyone who is not premium listens with ads." If the app adds a third plan in the future, it will also fall into ELSE and look like "With ads"; if the rule changes, a new branch has to be added.