…
…
SQL and Database Fundamentals · Lesson 5 / 41 · SELECT and filtering
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.
Quick questions reach student services all day long: how many students come from Toronto, Lisbon, and Seoul, which courses have "Database" in their name, who was born in 2007, and how many students have a student email address. You could write all of them with the =, <, > and AND/OR you already know, but the conditions get long and mistakes get easy.
In lesson 4 you built conditions with comparison operators and AND, OR, NOT. To say "Toronto, Lisbon, or Seoul" you joined three equalities with OR; to say "GPA between 2 and 3" you combined two comparisons with AND. Those forms work, but some patterns come up so often that SQL offers shortcuts for them. A shortcut is not only less typing: the shorter a condition gets, the easier it is to read, and a wrongly written part stands out sooner.
In this lesson you will:
IN and a range with BETWEEN.LIKE and ILIKE.Asking whether a column equals one of several values is very common: three cities, two departments, four letter grades. Written as an OR chain, the column name is repeated every time: city = 'Toronto' OR city = 'Lisbon' OR city = 'Seoul'. If you want to add one more city, the chain grows; if you misspell the column name somewhere, or write AND instead of OR, the mistake is easy to miss.
IN asks the same question with one condition: city IN ('Toronto', 'Lisbon', 'Seoul'). The values go in parentheses, separated by commas. The quote rule is the same as in lesson 4: text and dates in single quotes, numbers without quotes. If the value in the row equals any value in the list, the condition is true and the row enters the result. The comparison is still letter by letter; if you write 'lisbon' in the list, students stored as Lisbon do not come back.
SELECT first_name, last_name, city FROM student WHERE city IN ('Toronto', 'Lisbon', 'Seoul');
| first_name | last_name | city |
|---|---|---|
| Jin | Singh | Toronto |
| Liam | Petrov | Seoul |
| Yuki | Johansson | Lisbon |
| Adaeze | Müller | Seoul |
| Mateo | Abara | Lisbon |
(first 5 of 27 rows)
The result has 27 rows. We show only five of them here; the order the rows come in is not guaranteed, and you will learn sorting in the next lesson. If you put NOT before the list, you ask the opposite: city NOT IN ('Toronto', 'Lisbon', 'Seoul') returns students from anywhere other than these three cities. It works the same way with numbers: year NOT IN (1, 2) returns the third- and fourth-year students.
When you move to the short form, the first question that comes to mind is: "Does IN really do the same thing as the OR chain?" Instead of arguing about it, it is best to try. You write the same question in both forms and look at the row count of each. COUNT(*) is perfect for this: if two queries give the same number, they selected the same rows. In the cell below, two queries sit one under the other. The cell shows only the result of the last query: run it as it is first (you get the result of the IN query), then delete the second query and run it again (you get the result of the OR chain). Both numbers should be 27. Then try two tasks: add 'Nairobi' to the list and see the count go up to 35; after that, write NOT IN instead of IN.
Try it now· not graded; doesn't affect progress
With NOT IN the count is 93: 27 + 93 = 120, all the students in the table. Adding the counts of a condition and its opposite and arriving at the row count of the table is a good check that your condition is sound. This check may fail on columns that contain empty values; you will see why in lesson 7.
The second common pattern is a range: "GPA between 2 and 3", "midterm between 40 and 59", "born in 2007". BETWEEN a AND b writes it as one condition and means exactly column >= a AND column <= b. Both ends are included. A student whose GPA is exactly 2 appears in the result of gpa BETWEEN 2 AND 3; a student with exactly 3 would appear too.
BETWEEN works with dates too. "Born in 2007" means the birth date is between January 1, 2007 and December 31, 2007:
SELECT COUNT(*) FROM student WHERE birth_date BETWEEN '2007-01-01' AND '2007-12-31';
| count |
|---|
| 35 |
(1 row)
Dates are written in single quotes and in year-month-day order, as in lesson 4. Including the ends helps here: a student born on January 1 or December 31 is counted too. Forgetting that the ends are included is a common mistake. Work out the difference between the two conditions in the question below.
WHERE gpa BETWEEN 2 AND 3 returned 36 rows. How many rows does the query below return?
SELECT COUNT(*) FROM student WHERE gpa > 2 AND gpa < 3;
The order matters in BETWEEN: the small value first, then the large value. gpa BETWEEN 3 AND 2 does not raise an error but returns no rows, because it means gpa >= 3 AND gpa <= 2, and no number can be both greater than 3 and less than 2 at the same time. Since there is no error message, you can catch this mistake only by looking at the result: if a range you expected returns 0 rows, check the order of the ends first. If you want the opposite, you write NOT BETWEEN: gpa NOT BETWEEN 2 AND 3 returns those below 2 and those above 3.
The third pattern is searching for a part of a text instead of the whole text: courses with "Database" in their name, codes that start with "SWE", emails that end with a certain domain. Equality (=) does not help here, because you would need to know the whole value. LIKE compares text with a pattern. A pattern has two wildcard characters:
| Wildcard | Meaning | Example pattern | Matches |
|---|---|---|---|
% | Any number of characters (including zero) | 'SWE%' | SWE101, SWE302 |
_ | Exactly one character | 'A_' | AA, AB (two characters, starting with A) |
Put % at the start and it means "ends with"; put it at the end and it means "starts with"; put it on both sides and it means "contains". Since % also covers zero characters, the pattern '%Database%' also finds courses whose name starts directly with "Database".
SELECT code, name FROM course WHERE name LIKE '%Database%';
| code | name |
|---|---|
| CPR103 | Databases I |
| CPR104 | Databases II |
| SWE203 | Database Systems |
| MIS202 | Database Management |
(4 rows)
The underscore asks about position. Course codes are six characters long; the fourth character shows the year of the course (CPR103 is a first-year course). In the pattern code LIKE '___1__' there are first three underscores (any three characters), then 1, then two more underscores: codes that are six characters long with a 1 in the fourth place. This query returns the 16 first-year courses. Match each pattern with the text it finds.
Which texts does each pattern find?
For each row, pick its match from the list, then check.
'SWE%''%II''%Intro%''___1__''A_'LIKE tells capital letters from lowercase letters, just like equality in lesson 4: the pattern '%programming%' does not find a course name that has "Programming" with a capital P. ILIKE, which is specific to PostgreSQL, searches for the same pattern without looking at letter case. In the case database this has a real effect: some students' email addresses were entered entirely in capital letters (like ISABELLA.POPESCU@STUDENTS.NORTHBRIDGE.EXAMPLE). email LIKE '%@students.northbridge.example' finds 97 students; the same pattern with ILIKE finds 104. The 7 students in between are the ones whose addresses were written in capitals.
ILIKE is not standard SQL; it may not work in other database systems. It is one example of the dialect differences you saw in lesson 1. You will see how to ignore letter case in other systems in lesson 26. In the cell below, the "Database" query is ready. Run it first, then try three tasks: find the courses with programming in the name (5 rows); do the same search with ILIKE '%programming%' and compare the results; finally, find the courses whose code starts with BUS.
Try it now· not graded; doesn't affect progress
It is easy to think of LIKE as meaning "contains", but LIKE does not say "contains" by itself; % gives it that meaning. If there is no wildcard in the pattern, LIKE and ILIKE work like equality: the value must equal the whole pattern letter by letter (except for letter case with ILIKE).
How many rows does this query return?
SELECT COUNT(*) FROM student WHERE email ILIKE '@students.northbridge.example';
There is no error message here either; the query runs and returns 0. When you see 0 rows, make it a habit to ask: "Is there really nothing, or is the pattern wrong?"
All three tools are conditions; wherever you can write a condition in WHERE, you can use them. That is why they combine with the AND, OR, NOT, and parentheses from lesson 4. In the question "courses whose code ends with 1__, that is, first-year courses, and whose credits are between 3 and 4", a pattern and a range are joined with AND:
SELECT code, name, credits FROM course WHERE code LIKE '%1__' AND credits BETWEEN 3 AND 4;
| code | name | credits |
|---|---|---|
| CPR101 | Algorithms and Programming I | 4 |
| CPR102 | Algorithms and Programming II | 4 |
| CPR103 | Databases I | 3 |
| CPR104 | Databases II | 3 |
(first 4 of 13 rows)
The AND inside BETWEEN 3 AND 4 is part of the range; the AND that joins the two conditions comes after it. To avoid confusion when reading, it helps to write each condition on its own line. When choosing a tool, look at the clue words in the business question: "one of these" wants a list (IN), "between" wants a range (BETWEEN), "starts with, ends with, contains" wants a pattern (LIKE). Match each job with the right tool.
Which tool for each job?
For each row, pick its match from the list, then check.
@students.northbridge.example in capital or lowercase lettersNow combine the tools in one query. You are asked for the students born in 2007 in the first three departments (departments 1, 2, and 3). Put the lines in the right order.
Put the lines of the query that returns the 2007-born students of departments 1, 2, and 3 in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
These tools work the same way in every table. Remember the library app from lesson 1: the book table has six books, and its columns are id, title, author, pages, and year. The librarian asks three things: the books with "The" in their title, the books between 200 and 300 pages, and the result of a search typed in lowercase.
SELECT title, author FROM book WHERE title LIKE '%The%';
| title | author |
|---|---|
| The Midnight Library | Matt Haig |
| The Alchemist | Paulo Coelho |
| The Little Prince | Antoine de Saint-Exupery |
(3 rows)
"The" was found at the start of the title because there is a % on both sides of the pattern and % also covers zero characters. For the page range, BETWEEN is enough:
SELECT title, pages FROM book WHERE pages BETWEEN 200 AND 300;
| title | pages |
|---|---|
| The Midnight Library | 288 |
| Pride and Prejudice | 279 |
| Things Fall Apart | 209 |
(3 rows)
A reader types "the" in the library's search box, in lowercase.
How many rows does this query return?
SELECT title FROM book WHERE title LIKE '%the%';
In search boxes where you cannot know what readers will type, ILIKE is more useful for this reason. For values with a fixed form, such as codes, LIKE is enough and states the intent more clearly.
Each underscore matches exactly one character; the 1 in the fourth position shows that the code belongs to a first-year course.
SELECT code, name FROM course WHERE code LIKE '___1__';
| code | name |
|---|---|
| CPR101 | Algorithms and Programming I |
| CPR102 | Algorithms and Programming II |
| CPR103 | Databases I |
| CPR104 | Databases II |
| SWE101 | Introduction to Programming |
(first 5 of 16 rows)
code LIKE '%1__' gives the same result, because all the codes are six characters long. The pattern with underscores also checks the length of the code: if there were a code with five or seven characters, it would not take it.
In the listener table of the Earbud music app, the premium members in three cities are wanted. The list is written with IN, and the plan with equality.
Forgetting the wildcard or putting it in the wrong place. Someone who counts the student email addresses forgets to put % at the start of the pattern:
SELECT COUNT(*) FROM student WHERE email ILIKE '@students.northbridge.example';
The query does not raise an error but returns 0, because without a wildcard ILIKE works like equality. For "ends with" the % goes at the start: '%@students.northbridge.example' (104). For "starts with" it goes at the end ('SWE%'), and for "contains" on both sides ('%Database%'). PostgreSQL not raising an error does not mean the condition is right; check it by looking at the row count of the result.
IN (list) asks whether a value equals one of the values in the list and gives the same result as a long OR chain; NOT IN returns everything outside the list.BETWEEN a AND b means >= a AND <= b: both ends are included, the small value is written first (BETWEEN 3 AND 2 returns empty without an error); it works with numbers and dates.LIKE searches with a pattern: % is any number of characters (including zero), _ is exactly one character; LIKE is case-sensitive, ILIKE (specific to PostgreSQL) is not, and a pattern without wildcards is equality.Next lesson: you will sort results, take the first N rows, and drop duplicates.
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.
SELECT nickname, city FROM listener WHERE city IN ('Seoul', 'Manila', 'Mumbai') AND plan = 'premium';
| nickname | city |
|---|---|
| sea_lighthouse | Manila |
| coffee_lover | Mumbai |
| hourglass | Seoul |
(3 rows)