…
…
SQL and Database Fundamentals · Lesson 7 / 41 · Sorting and NULL
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 advising office wants three lists: students with no GPA, records with a missing email, and students with no advisor assigned. Your first attempt was WHERE gpa = NULL; the query did not fail, but it returned no rows at all. You cannot produce these lists correctly until you learn how blank values behave in SQL.
So far, every cell in the queries you wrote had a value, or you assumed it did. In real databases some cells are blank: the information does not exist yet, nobody entered it, or it has no meaning for that record. In this lesson you will learn to work with blank cells correctly. By the end you will be able to produce the advising office's three lists without mistakes, notice when blanks disappear from a "who is not X" question, and show a meaningful text in a report instead of a blank.
In this lesson you will:
IS NULL and IS NOT NULL.COALESCE.First, let's look at where the student records database has blanks. When you browsed the tables in lesson 2, you saw "no value" in some cells. Counted, the table looks like this:
| Table | Column | Blank rows | Why blank? |
|---|---|---|---|
student | gpa | 32 (29 are first-year) | No grades yet |
student | email | 9 | The student gave no address |
student | advisor_id | 8 | No advisor assigned |
enrollment | final_exam | 310 | This term's final has not been taken yet |
course | department_id | 4 | Shared courses belong to no department |
The advising office's three lists are about exactly these blanks. So this lesson is not just a technical detail: if you cannot find the blanks in the data correctly, you will give the wrong answer to the question the office is really asking.
In SQL, the name of a blank cell is NULL. NULL means "no value" or "unknown". It is not zero: a student whose GPA is NULL does not have a GPA of 0; the GPA has not been calculated yet. It is not an empty string ('') either: an empty string is a value that was entered, it just has no characters in it. And it is certainly not a space character.
This difference matters in the case too. The cells of the 9 students without an email are NULL; if you wrote WHERE email = '', no rows would come back, because nobody's address was entered as an empty string. In another database, someone may have saved the blanks as ''. Do not count before you know which one is used; first look inside the column, as you did in lesson 2.
The advising office's first question: which students have no GPA? The first idea that comes to mind is to write WHERE gpa = NULL. Predict the result first.
There are 32 students with a blank GPA. How many rows does this query return?
SELECT COUNT(*) FROM student WHERE gpa = NULL;
The first rule about NULL is surprising: NULL is not equal to anything, not even to itself. When you compare an unknown value with an unknown value, you cannot say "equal"; the answer is unknown too. Because WHERE keeps only the rows where the condition is true, WHERE gpa = NULL returns no rows. The most dangerous part is that it does not raise an error either: the query runs, the result comes back empty, and you think "nobody is missing a GPA".
There is a special operator for finding blank values: `IS NULL`. For filled values you write `IS NOT NULL`. These are not comparisons; they ask "is this cell blank?", and the answer is always true or false.
Let's narrow the office's question a little. It is normal for first-year students to have no GPA; but students in their second year or above who still have a blank GPA should be looked at. You join the two conditions with AND, as in lesson 4:
SELECT student_no, first_name, year FROM student WHERE gpa IS NULL AND year > 1;
| student_no | first_name | year |
|---|---|---|
| 202402002 | Yuki | 3 |
| 202504003 | Hiro | 2 |
| 202405006 | Mohammed | 3 |
(3 rows)
Of the 32 students with a blank GPA, 29 are first-year; the remaining three are in upper years but have no grades at all. These are the first people the advising office will call. Now you try: run the query, then write IS NOT NULL instead of IS NULL and find how many students have a GPA (88 rows should come back). Finally, change the condition to email IS NULL and get the students with a missing email (9 rows).
Try it now· not graded; doesn't affect progress
Why does = NULL give "unknown" and not "false"? Because in SQL a condition has three possible results: true, false and unknown. This is called three-valued logic. The result of a comparison that involves NULL is always unknown. WHERE keeps only the true ones; both false and unknown are left out.
The consequence looks strange at first. Count the students with a GPA below 2:
SELECT COUNT(*) FROM student WHERE gpa < 2;
| count |
|---|
| 25 |
(1 row)
Now take the opposite with NOT, from lesson 4: WHERE NOT (gpa < 2). This query returns 63. Add the two and you get 25 + 63 = 88, while the number of students is 120. A condition and its opposite feel like they should cover all rows, but they do not. The 32 missing students are the ones whose GPA is NULL: for them gpa < 2 is unknown, and the opposite of "unknown" is also unknown. They are in neither query.
| Result of the condition | Rows | Who? |
|---|---|---|
True (gpa < 2) | 25 | GPA below 2 |
False (not gpa < 2) | 63 | GPA 2 or above |
| Unknown | 32 | GPA is NULL |
| Total | 120 |
The rule: if a column has NULL, taking the opposite of a condition does not split the rows into exactly two; a third group remains, the unknown group. Below, think of a single student whose GPA is NULL and match what each expression gives for that student.
For a student whose GPA is NULL, what is the result of each expression?
For each row, pick its match from the list, then check.
gpa < 2NOT (gpa < 2)gpa IS NULLgpa IS NOT NULLgpa = NULLThree-valued logic hurts most in "who is not X" questions. The office asks for the students that instructor 12 does not advise. First, let's see how many advisees that instructor has:
SELECT COUNT(*) FROM student WHERE advisor_id = 12;
| count |
|---|
| 7 |
(1 row)
There are 120 students, and seven are this instructor's. So the "not" group should be 113. Predict before you write the query.
Instructor 12 has 7 advisees and there are 120 students. How many rows does this query return?
SELECT COUNT(*) FROM student WHERE advisor_id <> 12;
The query returns 105; 7 + 105 = 112, and the 8 missing students are the ones who have never been assigned an advisor. <> means "not equal", but for NULL, "not equal" is also unknown. The same trap exists in the other "not" tools from lesson 5: NOT IN and NOT LIKE also quietly leave NULL rows out. If you write department_id NOT IN (1, 2) in the course catalog, 19 courses come back; the 4 shared courses without a department (Academic Writing, Quantitative Reasoning I and II, Information Technology Skills) are not in the list.
If the blanks are wanted too, you add them explicitly: OR column IS NULL next to the condition. So the advisor question becomes WHERE advisor_id <> 12 OR advisor_id IS NULL and 113 rows come back; the catalog question gives 23 courses. Which one is correct depends on the question: "students who have an advisor other than instructor 12" is 105, "everyone who is not an advisee of instructor 12" is 113. When you read a question, decide whether the blanks should be in or out.
The query below returns 105. Change the condition so that students without an advisor are counted too; you should see 113.
Try it now· not graded; doesn't affect progress
NULL affects not only comparisons but also calculations. Every arithmetic operation with NULL gives NULL: if you add 1 to an unknown number, the result is unknown too. The score 0.4 * midterm + 0.6 * final_exam you wrote in lesson 3 returns NULL for records without a final. In text joining with ||, if one part is NULL, the whole result is NULL. Predict first.
What does this query return?
SELECT 72 * 0.4 + NULL * 0.6;
Sometimes you want to show a value in place of a blank. The tool for that is `COALESCE`. COALESCE(a, b, c) looks at the values from left to right and returns the first one that is not NULL. COALESCE(email, 'no address') gives the email if there is one, otherwise the text "no address".
But be careful: what to fill a blank with is not a technical choice, it is a business rule. Let's calculate the score in two ways for the records whose final has not been taken this term:
SELECT student_id, midterm, final_exam, 0.4 * midterm + 0.6 * final_exam AS score, 0.4 * midterm + 0.6 * COALESCE(final_exam, 0) AS zeroed FROM enrollment WHERE final_exam IS NULL ORDER BY student_id, midterm LIMIT 3;
| student_id | midterm | final_exam | score | zeroed |
|---|---|---|---|---|
| 1 | 72 | NULL | NULL | 28.8 |
| 1 | 99 | NULL | NULL | 39.6 |
| 2 | 65 | NULL | NULL | 26 |
(3 rows; 310 without LIMIT)
The score column is honest: there is no final, so there is no score. The zeroed column shows the 310 records whose final has not been taken as if they got zero; a student with a midterm of 72 looks like they stopped at 28.8. But the student has not taken the exam yet. Filling with zero is correct only if there is a rule that says "a student who skips the exam gets zero" and the exam is over. If you are not sure, leave the NULL or show a text such as "Awaiting final" in the report.
There is also a blank among the sections: 4 sections have no room, because they are held online. Run the query, then write COALESCE(room, 'Online') AS room instead of room and see "Online" in the blank cells.
Try it now· not graded; doesn't affect progress
NULLs come from three sources. The first is information that does not exist yet: if the final exam has not been taken, there is no final grade, and if there is no grade, there is no GPA either. The second is optional information: not every student has to give an email address, and shared courses have no department. The third is that the query itself can produce NULL: when you join tables, unmatched rows are filled with NULLs; you will see this in lesson 16.
You have met NULL before. In lesson 6 you learned that in sorting, NULLs go last in ascending order and first in descending order, and that you can choose their place with NULLS LAST. COUNT(*) in lesson 2 counts rows and does not look at whether a cell is filled; that is why in this lesson you counted blanks by using COUNT(*) with the right condition (WHERE ... IS NULL). The form that counts the filled values of a column directly you will learn in lesson 11.
NULL is not a bad thing; it tells the truth correctly. If you do not know a value, leaving NULL instead of writing a made-up value (0, "-", 1900-01-01) keeps the data honest. A phone number or a GPA written as zero later gets mixed into calculations like a real value; NULL says "we don't know" and forces the person writing queries to be careful. What matters is to take NULLs into account when you write a query.
Now put everything in this section together. Arrange the lines below into a query that lists all students whose advisor is not 12 (including those with no advisor), sorted by last name.
All students whose advisor is not 12, including those without an advisor, sorted by last name.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The NULL rules are the same in every database. Think of the shipment table of a delivery company; its columns are no, recipient, courier and delivery_date. In an undelivered shipment the delivery date is blank, and in a shipment with no courier assigned the courier is blank:
| no | recipient | courier | delivery_date |
|---|---|---|---|
| 1 | Anna | Hugo | 2026-11-20 |
| 2 | Ben | NULL | NULL |
| 3 | Chen | Hugo | NULL |
| 4 | Dina | Sara | 2026-11-22 |
| 5 | Eli | Sara | 2026-11-25 |
Shipments that have not been delivered yet:
SELECT no, recipient FROM shipment WHERE delivery_date IS NULL;
| no | recipient |
|---|---|
| 2 | Ben |
| 3 | Chen |
(2 rows)
In the report, write "unassigned" for a shipment whose courier is blank:
SELECT no, recipient, COALESCE(courier, 'unassigned') AS courier FROM shipment ORDER BY no;
| no | recipient | courier |
|---|---|---|
| 1 | Anna | Hugo |
| 2 | Ben | unassigned |
| 3 | Chen | Hugo |
| 4 | Dina | Sara |
| 5 | Eli | Sara |
(5 rows)
So how many shipments were not carried by Hugo? Predict.
In the shipment table above, how many rows does this query return?
SELECT COUNT(*) FROM shipment WHERE courier <> 'Hugo';
The advising office's second list: students with a missing email. In the address column, write "no address" instead of a blank cell.
SELECT first_name, last_name, COALESCE(email, 'no address') AS email FROM student WHERE email IS NULL;
| first_name | last_name | |
|---|---|---|
| Nadia | Santos | no address |
| Kenji | Novak | no address |
| Mohammed | Cohen | no address |
| Ali | Chen | no address |
| Jin | Tanaka | no address |
| Ivan | Lindqvist | no address |
Searching for blank values with `= NULL` or `<> NULL`.
OutputSELECT first_name FROM student WHERE gpa = NULL; -- 0 rows, no error
SELECT first_name FROM student WHERE gpa IS NULL; -- 32 rowsPostgreSQL does not raise an error for the first query, it only returns an empty result; that is why it is hard to notice. = NULL gives unknown for every row and WHERE keeps none of them. The same goes for <> NULL: if you write WHERE gpa <> NULL to get "students who have a GPA", you again get 0 rows; the correct form is IS NOT NULL (88 rows). A NULL check is always done with IS NULL or IS NOT NULL.
= NULL matches no row; blanks are found with IS NULL and filled values with IS NOT NULL.<>, NOT IN, NOT LIKE and NOT (...) do not cover blank rows; if the blanks are wanted, OR column IS NULL is added (113 instead of 105 in the advisor question).|| joining; COALESCE gives the first filled value and is used to show a text in place of a blank in a report, but counting a blank as 0 depends on the business rule.Next lesson: You will use CASE to split values (including NULL) into labels.
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.
course_offering |
room |
| 4 |
| No room given to the section |
| Lindqvist |
| no address |
| Tariq | Patel | no address |
| Nikolai | Haddad | no address |
(9 rows)
AS email gives the column its old name again; the person reading the report sees the situation clearly instead of a blank cell.
Without a table, let's try three operations side by side: text joining, addition and COALESCE.
SELECT 'a' || NULL AS concatenation, NULL + 1 AS addition, COALESCE(NULL, 0) AS default_value;
| concatenation | addition | default_value |
|---|---|---|
| NULL | NULL | 0 |
(1 row)
The concatenation and the addition gave NULL, because one of the parts is unknown. COALESCE moved on to the second value, 0, because the first value is NULL.