…
…
SQL and Database Fundamentals · Lesson 6 / 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 dean's office wants an honor list of the five students with the highest GPA. Management also wants to see which cities the students come from, with each city written once. Both lists must come out in the same order on every run.
In lesson 2 you saw something important: the rows in a table have no natural order. When you write SELECT * FROM student;, the rows come in whatever order the database finds convenient at that moment. Today they come one way; tomorrow, after a row has been updated, they may come another way. This has not been a problem so far, because you were asking only "which rows?". The dean's question is different: "top five" means first sorting all the students by GPA, then taking the first five. In this lesson you will learn three tools: ORDER BY to sort, LIMIT (and OFFSET to skip) to take a certain number of rows from the start, and DISTINCT to drop repeated rows.
At the end of the lesson, the honor list you write will look like this:
| student_no | first_name | last_name | gpa |
|---|---|---|---|
| 202407009 | Omar | Kim | 4 |
| 202502007 | Noor | García | 4 |
| 202302001 | Camila | Osei | 3.88 |
| 202405001 | Anika | Rivera | 3.88 |
| 202304004 | Zara | Larsen | 3.85 |
It looks simple, but there are three traps behind it: students whose GPA is empty, students with the same GPA, and a list that is cut before it is sorted. We will see them all in turn.
ORDER BY sorts the result by a column. It is written at the end of the query, after WHERE if there is one: SELECT first_name, last_name, hire_date FROM instructor ORDER BY hire_date;. The default direction is smallest to largest, that is ASC (ascending); you can leave it out. To sort from largest to smallest you write DESC (descending) after the column name.
What counts as "small" or "large"? It depends on the type of the column. Numbers are ordered by numeric size: 0.14, 0.5, 3.88, 4. Dates are ordered by the calendar: an old date is small, a new date is large. Text is ordered by letters: A first, Z last. That is why the question "who started most recently" is answered with hire_date DESC, and "who started earliest" with hire_date (or ASC).
Let's ask for the three instructors who started most recently:
SELECT first_name, last_name, hire_date FROM instructor ORDER BY hire_date DESC LIMIT 3;
| first_name | last_name | hire_date |
|---|---|---|
| Yuki | Cohen | 2026-02-01 |
| Clara | Abara | 2024-09-01 |
| Lucía | Kowalski | 2022-09-01 |
(3 rows)
DESC put the newest date on top; the LIMIT 3 at the end cut the list at three rows. We will look at LIMIT separately in a moment. In the cell below, the query is in ascending order: the instructor who started earliest (2005) is on top. Run it, then try two tasks:
1. Put the newest starter on top.
2. Sort the list by last name instead of by date.
Try it now· not graded; doesn't affect progress
Look carefully at the second task: there are two instructors with the same last name (Cohen, Kowalski, Müller, Reyes). What will be the order between them? The answer to this question is in section 3.
ORDER BY runs after the calculations in SELECT. That is why you can use the alias you learned in lesson 3 in ORDER BY: SELECT first_name, last_name, gpa * 25 AS score_100 FROM student ORDER BY score_100 DESC NULLS LAST, student_no LIMIT 3; is valid and returns Omar Kim and Noor García (100) on top. In WHERE, though, you cannot use an alias; you will see the reason in lesson 9, when we look at the order in which a query runs. You can also write the position number of the column (ORDER BY 2), but when the column list changes, the query silently sorts by the wrong column; that is why writing the name is safer.
LIMIT n returns at most n rows of the result. It is written at the very end of the query, after ORDER BY. It does not sort by itself; it only says "take n from the start of the list as arranged so far". If the table has fewer than n rows, you get all of them, and no error occurs.
Here is the first trap: LIMIT 5 does not mean "best 5". If you write SELECT first_name, gpa FROM student LIMIT 5; you get five students, but which ones is not defined. Since the rows have no natural order, the database gives you the first five rows it happens to reach. Among those five there might be the student with the lowest GPA, or one whose GPA is empty. In questions such as "top five", "newest three", and "the fullest section", LIMIT always comes together with ORDER BY: first arrange, then cut.
Now let's write the honor list. The first attempt is the most natural query: sort by GPA in descending order, take the first five. But the NULL you met in lesson 2, that is, "no value", gets involved here. Because the first-year students who enrolled this year have no grades yet, the gpa column is empty for 32 students. When sorting, PostgreSQL treats NULL as larger than every value: in ascending order NULLs come last, and in descending order they come first.
Who appears in the first rows of this query?
SELECT first_name, last_name, gpa FROM student ORDER BY gpa DESC LIMIT 3;
The fix is to add NULLS LAST: ORDER BY gpa DESC NULLS LAST sends the empty values to the end of the list. If you want the opposite, you write NULLS FIRST; for example, for a checklist that says "students whose grades are not entered yet should appear on top".
Example 1: The honor list.
SELECT student_no, first_name, last_name, gpa FROM student ORDER BY gpa DESC NULLS LAST, student_no LIMIT 5;
| student_no | first_name | last_name | gpa |
|---|---|---|---|
| 202407009 | Omar | Kim | 4 |
| 202502007 | Noor | García | 4 |
| 202302001 | Camila | Osei | 3.88 |
| 202405001 | Anika | Rivera | 3.88 |
| 202304004 | Zara | Larsen | 3.85 |
(5 rows)
Why is student_no at the end? Two students have a GPA of 4, and two have 3.88. We will explain it in the next section. First, try two things in the cell:
1. Delete the words NULLS LAST and run it again. What changed in the first rows?
2. Reverse the list: get the five students with the lowest GPA. (What should you write instead of DESC NULLS LAST? In ascending order, where do NULLs already fall?)
Try it now· not graded; doesn't affect progress
For the second task ORDER BY gpa, student_no is enough: in ascending order NULLs are already at the end and do not get into the lowest five. On top comes Adaeze Álvarez with a GPA of 0.14.
You can write several columns in ORDER BY, separated by commas. ORDER BY year DESC, last_name first sorts by year (from 4 to 1), and arranges the students in the same year among themselves by last name (A to Z). The direction of each column is set separately; DESC applies only to the column right before it. The second column comes into play only when there is a tie in the first column. If every value in the first column is different, the second column changes nothing.
Example 2: The heaviest courses. Let's arrange the catalog by credits in descending order, by ECTS in descending order when credits are equal, and by course code in ascending order if that is equal too:
SELECT code, credits, ects FROM course ORDER BY credits DESC, ects DESC, code LIMIT 6;
| code | credits | ects |
|---|---|---|
| SWE201 | 4 | 7 |
| CPR101 | 4 | 6 |
| CPR102 | 4 | 6 |
| SWE101 | 4 | 6 |
| SWE102 | 4 | 6 |
| IND201 | 3 | 6 |
(6 rows)
The first five courses have 4 credits. Among them, ECTS decided the order: SWE201, with 7 ECTS, is on top. Four courses have both 4 credits and 6 ECTS; the third column, the course code, decided their order.
Now the second trap: the order is not fixed in a tie. If two rows have the same value in the sorting column, the database freely chooses which comes first. Think of the query SELECT name, founded_year FROM department ORDER BY founded_year LIMIT 3;, which sorts the departments by founding year. Business Administration and Industrial Engineering were both founded in 1999. In one run Business Administration came first, but that is not a guarantee; on another day or on another server Industrial Engineering might come first. In third place is Psychology, founded in 2005. If you add a second column to the query, the uncertainty ends.
Example 3: The oldest departments.
SELECT name, founded_year FROM department ORDER BY founded_year, name LIMIT 3;
| name | founded_year |
|---|---|
| Business Administration | 1999 |
| Industrial Engineering | 1999 |
| Psychology | 2005 |
(3 rows)
Now the name breaks the tie in 1999: B comes before I. If you want the result to come out the same on every run, you add a unique column to the end of the sorting, that is, a column that is different in every row: student number, course code, id. Let's call this a tie-breaker. The student_no in the honor list is exactly this: it fixes the order of Omar and Noor, who have a 4, and of Camila and Anika, who have 3.88. In reports where the order matters, such as the honor list, this habit prevents the argument "yesterday Anika was third, today she is fourth" before it starts.
Put the lines of the query "the 5 fullest offerings this term (term_id = 3), by offering number when capacity is equal" in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
If you sorted the students by last name in the cell, you probably noticed this: the list runs from Abara to Yamamoto, and then Álvarez comes last, after Yamamoto. This is not a data error. The in-browser PostgreSQL you use in this course sorts text by the character code of the letters. Every letter has a number in the computer; the numbers of the 26 letters of the English alphabet go in alphabet order, but letters such as Á, é, ñ, and ü have much larger numbers. The result: values that start with such a letter fall after Z. If you sort the 120 students with ORDER BY last_name, the list ends with Tanaka, Yamamoto, and Álvarez.
The same rule applies to the letters inside a word. Here is a small demonstration:
SELECT n FROM (VALUES ('Mzimba'), ('Müller'), ('Muller')) AS t(n) ORDER BY n;
| n |
|---|
| Muller |
| Mzimba |
| Müller |
Müller comes after Mzimba, because the code of ü is larger than the code of z. Capital letters have smaller codes than lowercase letters, so a list that mixes cases puts all the capitals first: Zoe comes before abel. On a server set up with an English or Spanish sorting rule, these values would come to their proper places; that setting is made when the server is installed and is not our topic in this lesson. What matters for you is to know this when you read a result: Álvarez at the end of the list is not a mistake, it is the sorting rule of this environment.
Let's move to the second request from management: which cities do the students come from? SELECT city FROM student; returns 120 rows: one city for each student, with Port Alder dozens of times. We need a list where each city is written once.
DISTINCT comes right after SELECT and drops the repeated rows in the result. SELECT DISTINCT city FROM student; returns each city once.
Example 4: Titles.
SELECT DISTINCT title FROM instructor ORDER BY title;
| title |
|---|
| Assistant Professor |
| Associate Professor |
| Lecturer |
| Professor |
(4 rows)
There are 20 instructors but only 4 different titles. This is also the answer to "how many different values are there?": the number of rows in the result. On the site this number is written under the table. The form that counts the different values directly, COUNT(DISTINCT ...), you will see in lesson 11. When you use DISTINCT and ORDER BY together, the list is both free of repeats and sorted. Without sorting, the four titles would still come, but their order would be undefined.
The third trap is here: DISTINCT applies not only to the first column but to the whole row. If you write several columns, two rows count as repeated only if all their columns are the same.
The students are spread over 7 departments and there are 4 year levels. How many rows does this query return?
SELECT DISTINCT department_id, year FROM student;
Example 5: Department and year pairs.
SELECT DISTINCT department_id, year FROM student ORDER BY department_id, year;
Result (first 6 rows):
| department_id | year |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 2 | 4 |
(first 6 of 25 rows)
Department 1 is a two-year program (Computer Programming), so it has only years 1 and 2. The row department 1, year 1 and the row department 2, year 1 are different in the first column and the same in the second; both stay, because the row as a whole is different.
One more writing rule: DISTINCT always comes right after SELECT. A form like SELECT first_name, DISTINCT city FROM student; does not mean "make only the city free of repeats"; PostgreSQL does not run it at all and gives a syntax error at or near "DISTINCT" error. Wanting both the first name and a repeat-free city in one row is contradictory anyway: which of the first names of dozens of students from Port Alder would be written?
Now back to the city list. SELECT DISTINCT city FROM student ORDER BY city; returns 12 rows: it starts with Cairo, Lagos, Lima, and ends with Toronto and Warsaw. You do not see the rule from section 5 here, because no city name starts with an accented letter.
Choose the tool that answers each question.
For each row, pick its match from the list, then check.
The student services web page lists the course catalog with 5 courses per page. There are 33 courses; the first page shows the first 5 courses and the second page shows the next 5. For this, OFFSET joins LIMIT: OFFSET k skips the first k rows, and LIMIT n takes the n rows after that.
The formula is: if you show n rows per page, for page k you write LIMIT n OFFSET (k - 1) × n. The first page is OFFSET 0 (or you do not write OFFSET at all), the second page is LIMIT 5 OFFSET 5, the third page is LIMIT 5 OFFSET 10. ORDER BY is a must here too. If the order is undefined, a course you saw on page 1 may show up again on page 2, and another may never appear; because every page is a separate query, and every query may return the rows in the order it finds convenient.
Example 6: The second page of the catalog.
SELECT code, name FROM course ORDER BY code LIMIT 5 OFFSET 5;
| code | name |
|---|---|
| CPR101 | Algorithms and Programming I |
| CPR102 | Algorithms and Programming II |
| CPR103 | Databases I |
| CPR104 | Databases II |
| CPR205 | Web Programming |
(5 rows)
The first page had the five courses that start with BUS; OFFSET 5 skipped them and returned the next five. Since the course code is unique, no tie-breaker is needed here. Try two tasks in the cell:
1. Get the third page. In the first row you should see GEN101, and in the last row IND101.
2. What would the second page be if 10 courses were shown per page? It should start with GEN101 and end with MIS202.
Try it now· not graded; doesn't affect progress
The writing places of ORDER BY, LIMIT, and OFFSET are fixed: SELECT → FROM → WHERE → ORDER BY → LIMIT/OFFSET. If you write ORDER BY before WHERE, PostgreSQL does not run the query. PostgreSQL also accepts the form OFFSET 5 LIMIT 5, but the usual order is LIMIT ... OFFSET ....
The same rules apply in every table. Think of the table of an amateur league with six teams. The team table has the team's name, city, points, and goal difference (goals scored minus goals conceded):
| name | city | points | goal_difference |
|---|---|---|---|
| Eagles | Port Alder | 18 | 9 |
| Gulls | Lisbon | 18 | 12 |
| Lions | Port Alder | 15 | 4 |
| Bulls | Toronto | 15 | 6 |
| Hawks | Seoul | 12 | -2 |
| Bees | Toronto | 9 | -5 |
The league's rule is clear: the team with more points is on top, and if points are equal, the team with the better goal difference is on top.
Does this query show the league leader correctly?
SELECT name, points FROM team ORDER BY points DESC LIMIT 1;
Example 7: The top three (outside the case).
SELECT name, points, goal_difference FROM team ORDER BY points DESC, goal_difference DESC LIMIT 3;
| name | points | goal_difference |
|---|---|---|
| Gulls | 18 | 12 |
| Eagles | 18 | 9 |
| Bulls | 15 | 6 |
(3 rows)
The two pairs equal on points (18 and 15) were separated by goal difference. Here the goal difference is the league's own rule, so the tie-breaker comes from the business rule; the student number in the honor list, on the other hand, was there only to fix the order. Both do the same job: they make the result come out the same on every run.
Which cities have a team in the league? Each city once, in alphabetical order:
SELECT DISTINCT city FROM team ORDER BY city;
| city |
|---|
| Lisbon |
| Port Alder |
| Seoul |
| Toronto |
(4 rows)
Six teams come from four cities; Port Alder and Toronto appear twice each but were written once.
The Software Engineering students (department_id = 2), seniors first, and by last name within the same year; the first four rows:
SELECT first_name, last_name, year FROM student WHERE department_id = 2 ORDER BY year DESC, last_name, first_name LIMIT 4;
| first_name | last_name |
|---|
Forgetting the NULLs in the honor list. If you pull the honor list with ORDER BY gpa DESC LIMIT 5, the GPA comes out empty in all five rows. In one run the first three rows were:
| student_no | first_name | gpa |
|---|---|---|
| 202605001 | Jin | NULL |
| 202604001 | Felix | NULL |
| 202605002 | Nadia | NULL |
Because the query runs without an error, you notice the mistake only by looking at the result. The order among the students whose GPA is empty is not guaranteed either; in another run other names may come. The reason is that in PostgreSQL NULL comes first in descending order. The correct form is ORDER BY gpa DESC NULLS LAST, student_no: the empty ones go to the end, and the student number breaks the ties.
ORDER BY column [ASC|DESC] sorts the result; with several columns the second one comes into play only in a tie, and a unique column (a tie-breaker) added at the end fixes the order on every run. In PostgreSQL NULL comes first in descending order, and NULLS LAST moves it to the end.LIMIT n returns at most n rows and OFFSET k skips the first k rows; "top 5" and paging (LIMIT n OFFSET (page - 1) × n) make sense only with ORDER BY.DISTINCT comes right after SELECT and drops repeats by looking at the whole row; in this environment values that start with an accented letter such as Á are sorted by character code, so they fall to the end of the list.Next lesson: you will write queries that count and filter correctly with NULLs.
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.
| Rosa | Haddad | 4 |
| Pablo | Müller | 4 |
| Aisha | Nguyen | 4 |
| Camila | Osei | 4 |
(4 rows)
DESC applied only to year; the last names were arranged from A to Z. The first_name at the end fixes the order if two students have the same last name.