…
…
SQL and Database Fundamentals · Lesson 9 / 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 intern who worked in student services before you left a file of frequently used queries. Some of them raise errors, and some run but return wrong results. In this lesson you will fix all of them.
You have been writing queries for eight lessons: you picked columns, filtered rows, sorted, dealt with NULLs, and built labels with CASE. Along the way you saw a few error messages in the red box: relation ... does not exist in lesson 1, the syntax error from a single-quoted alias in lesson 3, and column "Toronto" does not exist from double-quoted text in lesson 4. So far we looked at those messages one by one. In this lesson you will gain two general skills. The first is knowing the order in which the database processes a query; this order answers most "why does this work but that doesn't?" questions. The second is reading an error message to find the problem, and catching a query that raises no error but is wrong.
The five queries in the intern's file are:
1. The top 5 GPAs among fourth-year students: raises an error.
2. Students whose score out of 100 is above 90: raises an error.
3. A list of first-year students: raises an error.
4. Name, last name, and year of students with a scholarship: runs, but the report came back.
5. Scholarship students in Lisbon or Toronto: runs, but returns 11 people, and the scholarship office says "that can't be right".
By the end of the lesson you will be able to say what is wrong in each of the five.
In this lesson you will:
You always write a query in the same order: SELECT, FROM, WHERE, ORDER BY, LIMIT. This order is a rule of the language; if you move the clauses around, the query does not run. But the database does not process the query in this order. It first needs to know which table to read from, so it starts with FROM. Then it filters the rows with WHERE. Only once the remaining rows are known does it choose the columns with SELECT, do the calculations, and assign aliases. After that it sorts with ORDER BY, and last it takes the requested number of rows from the top with LIMIT.
This is called the logical execution order: FROM → WHERE → SELECT → ORDER BY → LIMIT. Each step takes the intermediate table produced by the previous step and produces a new one. The rule comes down to one sentence: a step can only see what was produced before it. What the database really does inside (which row it reads first, which shortcut it takes) may differ, but the result always comes out as if it had worked in this order. In lesson 39 you will look at that inner workings too.
In the diagram, the only clause that changes place is SELECT: first when you write, third when it runs. Every surprising case comes from that one shift.
Example 1: The top 5 GPAs among fourth-year students. The correct version of the intern's first query:
SELECT first_name, last_name, gpa FROM student WHERE year = 4 ORDER BY gpa DESC NULLS LAST LIMIT 5;
| first_name | last_name | gpa |
|---|---|---|
| Camila | Osei | 3.88 |
| Zara | Larsen | 3.85 |
| Pablo | Müller | 3.77 |
| Anika | Park | 3.65 |
| Samuel | Rossi | 3.58 |
(5 rows)
We wrote the query with each clause on its own line; in long queries this makes reading and finding errors easier. Now follow this query in execution order and watch how many rows the intermediate table has at each step:
| Step | What it does | Intermediate table |
|---|---|---|
| FROM student | Takes all the students | 120 rows, 13 columns |
| WHERE year = 4 | Drops students who are not fourth-year | 21 rows |
| SELECT first_name, last_name, gpa | Picks three columns | 21 rows, 3 columns |
| ORDER BY gpa DESC NULLS LAST | Sorts from highest to lowest | 21 rows |
| LIMIT 5 | Takes 5 rows from the top | 5 rows |
Because LIMIT runs last, the "top 5" are the first 5 of the sorted list. If LIMIT ran before sorting, it would take 5 arbitrary students and then sort only those; it would not answer the question "the five highest". Now you build the order.
Put the clauses of the query in Example 1 in the order the database **runs** them.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Once you know the execution order, a few rules you might have memorized come out on their own. The most important one is about aliases: an alias you give in SELECT cannot be used in WHERE, but it can be used in ORDER BY. The reason is the order: when WHERE runs, SELECT has not run yet, so the alias has not been created. ORDER BY runs after SELECT and can see the alias.
Example 2: Using an alias in WHERE. The intern's second query wants students whose score out of 100 is above 90:
OutputSELECT first_name, gpa * 25 AS score FROM student WHERE score > 90;
column "score" does not existThe name score is clearly written in the query, yet the database says "there is no such column". It is right: at the moment WHERE runs, it has only the columns of the student table, and score is not among them. The fix is to write the calculation itself again in WHERE instead of the alias. In sorting, the alias can be used freely:
SELECT first_name, gpa * 25 AS score FROM student WHERE gpa * 25 > 90 ORDER BY score DESC, first_name;
| first_name | score |
|---|---|
| Noor | 100 |
| Omar | 100 |
| Anika | 97 |
| Camila | 97 |
| Zara | 96.25 |
| Kenji | 95.75 |
| Pablo | 94.25 |
| Ethan | 92.25 |
| Anika | 91.25 |
| Olivia | 90.25 |
(10 rows)
first_name was added as the second sort column so that students with equal scores come out in the same order every time (lesson 6). Writing the calculation twice may feel like needless repetition, but with this execution order there is no other way. You will see how to remove the repetition with a CTE in lesson 23.
Which of the two queries below runs?
A: SELECT first_name, gpa * 25 AS score FROM student WHERE score > 90;
B: SELECT first_name, gpa * 25 AS score FROM student ORDER BY score DESC;
In the cell below, the corrected query is ready. First run it as it is and see the 10 rows. Then replace gpa * 25 in the WHERE line with score, run it, and read the message in the red box. Undo that. Finally, raise the threshold to 95: how many students are left?
Try it now· not graded; doesn't affect progress
With a threshold of 95, 6 students are left: Noor, Omar, Anika, Camila, Zara, and Kenji. The same logic applies to labels you build with CASE: when you write CASE ... END AS status in lesson 8, status is also an alias, and WHERE status = 'Honors' raises the same error.
When a query raises an error on this site, a red box appears. The box shows PostgreSQL's message as a single line, with a short explanation below it under the heading "What does this mean?". In this lesson we write the messages the way you see them on the site, as a single line.
Later, when you work in a tool such as psql or pgAdmin, you will see the same message in a longer form:
OutputERROR: syntax error at or near "WHERE"
LINE 1: SELECT first_name, gpa FROM student ORDER BY gpa WHERE year = 4;
^The first line is the message you see on the site, with only ERROR: added at the start. The second line shows the relevant line of the query, and the ^ mark on the third line shows where the database got stuck. Whether the message is short or long, the way to read it is the same.
PostgreSQL's messages look English and technical at first glance, but almost all the messages you will meet as a beginner fit one of three patterns. The kind of the message tells you the kind of problem, and the quoted part shows where to look. Think of it as a crime-scene report: the kind of incident, the clue found at the scene, and the rule "look right next to the clue".
Example 3: Three kinds, with real messages. Each item shows a broken query and, below it, the message from the site.
Kind 1: table does not exist. In the message relation "x" does not exist, relation means table. The table name is misspelled, or there is no such table at all:
OutputSELECT first_name FROM students;
relation "students" does not existThe table is named student; because of the extra "s", the database is looking for a different table.
Kind 2: column does not exist. The message column "x" does not exist says that a name read as a column in the query is not in the table. There can be three causes. The most common is a typo:
OutputSELECT first_name, last_names FROM student;
column "last_names" does not existThe second is using an alias in WHERE: the column "score" does not exist in Example 2 was this. The third is writing text with double quotes. In SQL, double quotes are for names (columns, tables, aliases); the database takes what is inside the quotes for a column name:
OutputSELECT first_name FROM student WHERE city = "Toronto";
column "Toronto" does not existSo this message does not simply mean "you misspelled a column name"; it says "I read this name as a column and could not find it". You tell which cause it is by looking at the quoted part: last_names is a typo, score is an alias, Toronto is text.
Kind 3: syntax. The message syntax error at or near "x" says that while reading the query, the database met something it did not expect. The key point here: the database shows the place where it noticed the problem, not the place where the problem was made. The problem is often right before x:
OutputSELECT first_name, gpa FROM student ORDER BY gpa WHERE year = 4;
syntax error at or near "WHERE"WHERE is spelled correctly; the problem is its place. WHERE cannot come after ORDER BY, because in the writing order WHERE comes before it. After ORDER BY gpa, the database was expecting a comma or something like LIMIT, and it met WHERE.
OutputSELECT first_name, last_name, FROM student;
syntax error at or near "FROM"FROM is perfect too. The problem is the extra comma right before it: after the comma the database expects one more column, and FROM arrives.
OutputSELECT first_name, CASE WHEN gpa >= 3.5 THEN 'Honors' ELSE 'Regular' AS status FROM student;
syntax error at or near "AS"AS is correct as well. The CASE was opened but not closed with END; the database was expecting END after ELSE 'Regular' and saw AS.
Besides these three kinds, learn to recognize two more messages. A single quote that is never closed is a special case of a syntax error:
OutputSELECT first_name FROM student WHERE city = 'Toronto;
unterminated quoted string at or near "'Toronto;""Unterminated quoted string": 'Toronto was opened, there is no closing quote, and even the semicolon was swallowed into the text. Finally, if you compare a number column with text, you get a type mismatch message:
OutputSELECT first_name FROM student WHERE year = 'four';
invalid input syntax for type integer: "four"year is a column that holds integers (integer); the database tries to convert 'four' to a number and cannot. The fix is year = 4. You will see data types and conversions in detail in lesson 25; for now it is enough to recognize the message. Now match the messages with their causes.
Match each error message with its most likely cause.
For each row, pick its match from the list, then check.
relation "course_list" does not existcolumn "last_names" does not existcolumn "score" does not exist (score is defined in SELECT)syntax error at or near "WHERE" (WHERE comes after ORDER BY)syntax error at or near "AS" (query with CASE)unterminated quoted string at or near "'Toronto;"Try the rule of looking right before the clue in a syntax error.
What happens with this query?
SELECT first_name FROM student WHERE year = 4 has_scholarship = true;
When you meet an error message, the first thing to do is not to delete the query and write it again from scratch. In a rewritten query you can make the same mistake again or add a new one, and you also throw away the clue the message gave you. Instead, follow a short routine. The routine asks you to fix one thing at a time, because if a query has several errors, the database reports only the first one it meets. When you fix one and run again, the next one appears. This is not bad news: each message brings you one step closer.
Put the steps of the routine to follow when an error message appears in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Why is the last step of the routine there? Because the most dangerous errors are the ones that give no message. As long as the syntax is valid, the database runs your query; it cannot know what you meant. Assuming that a query is correct because it ran without an error is the most common cause of a wrong report. So whenever you look at a result, follow a short checklist, the way pilots do before takeoff.
Example 4: A missing comma. The intern's fourth query wants the first name, last name, and year of students with a scholarship:
SELECT first_name last_name, year FROM student WHERE has_scholarship;
| last_name | year |
|---|---|
| Anika | 4 |
| Anika | 3 |
| Kenji | 3 |
(3 of 28 rows)
There is no error, but the result has two columns, and under the last_name header there are first names. The comma between first_name and last_name was forgotten. In lesson 3 you saw that the word AS is optional: writing first_name last_name means first_name AS last_name to the database. So the first_name column came back with the alias last_name, and the real last name column was never selected. The row count is right (28 students with a scholarship), so someone who looks only at the row count misses the error; someone who looks at the headers catches it.
A friend shows you the result of the query in Example 4: the headers are last_name | year, and in the first rows the last_name column says Anika, Anika, Kenji. What happened?
Example 5: Precedence. The intern's fifth query wants "scholarship students who live in Lisbon or Toronto":
SELECT first_name, last_name, city FROM student WHERE city = 'Lisbon' OR city = 'Toronto' AND has_scholarship;
| first_name | last_name | city |
|---|---|---|
| Yuki | Johansson | Lisbon |
| Mateo | Abara | Lisbon |
| Salma | García | Lisbon |
(3 of 11 rows)
11 rows came back; the scholarship office says "we don't have that many scholarship students from Lisbon and Toronto". As you saw in lesson 4, AND binds before OR. The condition is actually read like this: city = 'Lisbon' OR (city = 'Toronto' AND has_scholarship). So everyone in Lisbon, with or without a scholarship, gets into the list, and the scholarship requirement applies only to Toronto. The way to find the mistake is to pick one row from the list and read the condition for that row: Yuki Johansson lives in Lisbon but has no scholarship; Yuki is in the list anyway, so the scholarship requirement was not applied to that row. The query fixed with parentheses:
SELECT first_name, last_name, city FROM student WHERE (city = 'Lisbon' OR city = 'Toronto') AND has_scholarship;
| first_name | last_name | city |
|---|---|---|
| Jin | Tanaka | Toronto |
| Nikolai | Álvarez | Toronto |
(2 rows)
The correct answer is 2 students; both are from Toronto, and there are no scholarship students in Lisbon. The difference between 11 and 2 shows why the row count must be checked. In the cell below, the query without parentheses is ready, and the has_scholarship column has been added so you can see whether each student has a scholarship. Run it, find someone without a scholarship in the list, read the condition for that person, and fix it with parentheses. How many rows are left?
Try it now· not graded; doesn't affect progress
A third way for a query to be silently wrong is choosing the wrong table or the wrong column; in lesson 2, a query asking for the number of course enrollments counted the student table instead of enrollment, so it returned 120 instead of 781, and no error message appeared. The cure for all of these is the same: set your expectation in advance. Ask "roughly how many rows should come back?" before running the query; if needed, find out the number separately with a small query such as SELECT COUNT(*) FROM student WHERE has_scholarship; (28), and compare the result with it.
The same messages appear in the same form in every database. Remember the library's book table from lesson 1: six books in a table with the columns id, title, author, pages, and year. Someone working at the library wrote these queries:
OutputSELECT title, author FROM book WHERE author = 'Matt Haig;
unterminated quoted string at or near "'Matt Haig;"
SELECT title, pages FROM book ORDER BY pages DESC WHERE year > 1950;
syntax error at or near "WHERE"
SELECT title, pages * 2 AS double_pages FROM book WHERE double_pages > 500;
column "double_pages" does not existIn the first one the closing quote is missing: 'Matt Haig'. In the second, WHERE must be written before ORDER BY. In the third, the alias was used in WHERE; the right way is WHERE pages * 2 > 500, and the result is The Midnight Library (576), Dune (1424), and The Time Regulation Institute (764). The fourth query does not raise an error:
OutputSELECT title author FROM book;How many columns does the result of this library query have, and what is the header?
SELECT title author FROM book;
At the end of the unit there is a workshop: in the earbud database you will answer eight questions without scaffolding. When you get an error there, you will follow the routine from this lesson. In the next unit, a new clause, GROUP BY, will enter this execution order between WHERE and SELECT.
The fixed version of the library's second query: books printed after 1950, from thickest to thinnest. WHERE took its place.
SELECT title, pages FROM book WHERE year > 1950 ORDER BY pages DESC;
| title | pages |
|---|---|
| Dune | 712 |
| The Time Regulation Institute | 382 |
| The Midnight Library | 288 |
| The Lantern Keeper | 240 |
| The Alchemist | 184 |
(5 rows)
Madonna in a Fur Coat (1943) was dropped at the WHERE step; sorting was applied only to the remaining five books.
There is one more query in the intern's file: list the honors students (GPA 3.5 and above) with a status column. First the END was missing (syntax error at or near "AS"
Trying to fix the word in the message. When you see syntax error at or near "WHERE", deleting WHERE or rewriting it:
OutputSELECT first_name, gpa FROM student ORDER BY gpa WHERE year = 4;
syntax error at or near "WHERE"If WHERE is deleted, the query runs, but the fourth-year filter is lost and all 120 students come back: a syntax error turns into a silent error. The word in the message is where the database got stuck, not the problem itself. The rule: look at that word and right before it. Here the problem is that ORDER BY comes before WHERE; the correct form is WHERE year = 4 ORDER BY gpa.
SELECT → FROM → WHERE → ORDER BY → LIMIT, and the execution order is FROM → WHERE → SELECT → ORDER BY → LIMIT; each step sees only what was produced before it, so an alias cannot be used in WHERE, can be used in ORDER BY, and LIMIT cuts the sorted result.relation ... does not exist is a table, column ... does not exist is a name read as a column (a typo, an alias in WHERE, or double-quoted text), and syntax error at or near "x" is syntax, where the problem is often right before x.AND/OR precedence); for every result, check the headers, the row count, and one row from the list, and when an error appears, fix one thing and run again.Next lesson: In the unit workshop, you will answer eight questions on your own in the earbud database.
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.
column "status" does not existWHERE status = 'Honors'SELECT first_name, last_name, CASE WHEN gpa >= 3.5 THEN 'Honors' ELSE 'Regular' END AS status FROM student WHERE gpa >= 3.5;
| first_name | last_name | status |
|---|---|---|
| Anika | Park | Honors |
| Anika | Rivera | Honors |
| Liam | Petrov | Honors |
(3 of 16 rows)
status is born in the SELECT step; WHERE cannot see it, so the condition is not the label itself but the comparison that produces the label.