…
…
SQL and Database Fundamentals · Lesson 4 / 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.
The scholarship committee is meeting and asks you for three lists: scholarship students whose GPA has dropped, scholarship students who live in Port Alder, and the second-year students of two software-focused departments. You do not need all 120 students, only the rows that match the condition.
Every query you have written so far returned all the rows of a table. In lesson 3 you chose which columns would come back and added calculated columns; but SELECT first_name, last_name FROM student; returned 120 rows every time. The committee's questions ask for choosing rows. "The scholarship students in Port Alder" is a handful of people among 120 rows. Dumping 120 rows on the screen and searching by eye is tiring and easy to get wrong; with 12,000 rows it would be impossible. In this lesson you will tell the database which rows you want with a condition.
In this lesson you will:
The WHERE clause is written after FROM and carries a condition. The database checks this condition separately for each row of the table. If the condition is true for that row, the row stays in the result; if it is false, the row is thrown away. SELECT decides which columns come back and WHERE decides which rows come back; the two are independent of each other.
Conditions mostly compare a column with a value. There are six comparison operators for this:
| Operator | Meaning | Example |
|---|---|---|
= | equal | year = 1 |
<> (or !=) | not equal | title <> 'Professor' |
< | less than | midterm < 50 |
> | greater than | year > 2 |
<= | less than or equal | gpa <= 2 |
>= | greater than or equal | gpa >= 3.5 |
Because we cannot type the "not equal" sign from math on a keyboard, SQL uses <>: "less or greater", that is, everything that is not equal. PostgreSQL also accepts !=; the two do the same job.
Example 1: Fourth-year students. The list of students who are close to graduating:
SELECT first_name, last_name, year FROM student WHERE year = 4;
| first_name | last_name | year |
|---|---|---|
| Anika | Park | 4 |
| Isabella | Popescu | 4 |
| Mateo | Abara | 4 |
| Lena | Nakamura | 4 |
(4 of 21 rows)
Of 120 students, 21 passed through the door. The attendant asked a single question for each row: "is the year value of this row equal to 4?" The rows of the result do not come in a particular order; you will learn ordering in lesson 6. For now, look at the row count: the result table on the site shows the total number of rows. A query is ready in the cell below. Run it as it is first, then try the three tasks:
1. Write > 2 instead of = 4. How many rows come back? (Third- and fourth-year students: it should be 56.)
2. Write <> 1 instead of > 2. How many students are not in the first year? (It should be 91.)
3. Apply the same idea to instructors: write SELECT first_name, last_name, title FROM instructor WHERE title <> 'Professor';. How many instructors are not professors? (It should be 16.)
Try it now· not graded; doesn't affect progress
In lesson 2 you saw that every column has a type. How you write the value in the condition depends on this type. Numbers are written without quotes: year = 4, gpa >= 3.5. The decimal separator is a point; because the comma separates lists in SQL, gpa >= 3,5 gives an error. Text is written inside single quotes: city = 'Toronto'. Double quotes do another job in SQL: as you saw with aliases in lesson 3, they surround a name (a column or table name). If you write city = "Toronto", PostgreSQL looks for a column named Toronto and gives this error:
Outputcolumn "Toronto" does not existThe message says exactly what happened: "there is no column called Toronto." You thought you wrote a value, but PostgreSQL read a name. Dates are also written inside single quotes, in year-month-day format, and they are compared in calendar order: birth_date < '2005-01-01' selects the people born before January 1, 2005. SELECT COUNT(*) FROM student WHERE birth_date < '2005-01-01'; returns 9; in the case there are 9 students born before 2005.
Text comparison is done letter by letter. If two texts are not exactly the same, they are not equal, including uppercase and lowercase letters, accents, and a trailing space. Try to predict the result of this rule.
In the case, 45 students live in Port Alder, and the city values are recorded as Port Alder. What does this query return?
SELECT COUNT(*) FROM student WHERE city = 'port alder';
That is why, when a condition returns fewer rows than you expected, first look at how the value is written in the table: seeing a few values by eye with SELECT city FROM student; is often enough. Real data also has dirty values that you cannot see by eye, such as a trailing space; in the case, one student's email address has an extra space at the end. You will learn the functions that clean text in lesson 26.
Columns of the true/false (BOOLEAN) type take the value true or false and are written without quotes: has_scholarship = true. Because the column itself is already true or false, you can also write simply WHERE has_scholarship; the attendant looks at the has_scholarship value of the row and lets it in if it is true. SELECT COUNT(*) FROM student WHERE has_scholarship; returns 28.
The committee's second question contains two requirements: living in Port Alder and having a scholarship. A single comparison cannot say that. You combine conditions with logical operators:
AND keeps a row if both conditions are true.OR keeps a row if at least one of the two conditions is true.NOT reverses a condition: it makes true false and false true. NOT has_scholarship selects the students without a scholarship; NOT year = 1 brings the same rows as year <> 1.This analogy gives you a practical check: if you add a new requirement to a condition with AND, the result gets smaller or stays the same, and never grows. If you add it with OR, the result grows or stays the same. If the opposite of what you expected happens, you have written the condition wrongly.
Example 2: Scholarship students in Port Alder.
SELECT first_name, last_name, city FROM student WHERE city = 'Port Alder' AND has_scholarship = true;
| first_name | last_name | city |
|---|---|---|
| Kenji | Osei | Port Alder |
| Tessa | Santos | Port Alder |
| Liam | Silva | Port Alder |
| Ivan | Lindqvist | Port Alder |
| Zara | Larsen | Port Alder |
| André | Costa | Port Alder |
(6 rows)
There are 45 students in Port Alder and 28 scholarship students at the school; only 6 people meet both. AND shortened the queue. The committee's second list is ready.
Example 3: Scholarship students whose GPA is low. The committee's first question: students who keep their scholarship but whose GPA has dropped below 2.5.
SELECT first_name, last_name, gpa FROM student WHERE has_scholarship AND gpa < 2.5;
| first_name | last_name | gpa |
|---|---|---|
| Kenji | Fernández | 2 |
| Lucas | Okafor | 1.92 |
| Ayesha | Singh | 1.59 |
| Maya | Rossi | 1.43 |
(4 of 15 rows)
The condition has two parts: has_scholarship (the true/false column itself) and gpa < 2.5. A row enters the list only if both are true. A query is ready in the cell below. Run it, then:
1. Lower the threshold to 2. Did the list get shorter? (It should be 12 rows.)
2. Set the threshold back to 2.5 and write NOT has_scholarship instead of has_scholarship. Who do you see now? (The 28 students who have no scholarship and a GPA below 2.5.)
Try it now· not graded; doesn't affect progress
NOT reversed only the condition right after it; gpa < 2.5 stayed as it was. So with the same query you answered two different questions: who has a scholarship at risk, and who is struggling without a scholarship.
The most common mistake when writing a condition is taking the operator word for word from the sentence. The request "bring the students in Toronto and Lisbon" has an "and" in it; but city = 'Toronto' AND city = 'Lisbon' returns no rows. A student's city cannot be both Toronto and Lisbon at the same time; the attendant asks every row "is your city Toronto AND at the same time Lisbon?" and the answer is "no" for every row. In everyday language, "the students in Toronto and Lisbon" really means "those in Toronto and those in Lisbon", that is, everyone from both cities: city = 'Toronto' OR city = 'Lisbon', and the result is 18 students.
The way out of this trap is to think about a single row before writing the condition. Ask yourself: "Maya lives in Toronto; should she be on this list?" She should. Is city = 'Toronto' AND city = 'Lisbon' true for Maya? No. So the condition is wrong. This small test with a single row makes you choose the operator by the intent, not by the word in the sentence.
Match each business sentence with the condition that meets it.
For each row, pick its match from the list, then check.
The committee's third question: the second-year students of departments 1 and 2 (Computer Programming and Software Engineering). The first way that comes to mind is: WHERE department_id = 1 OR department_id = 2 AND year = 2. The query runs and gives no error. But what does it bring?
In math, in 2 + 3 * 4 multiplication is done before addition, and the result is 14, not 20. SQL has a similar rule: `AND` is evaluated before `OR`. A condition is not read from left to right in the order it is written. First the two sides of AND combine, then OR comes. The diagram below shows two readings of the same condition.
The tree on the left shows how SQL reads the condition without parentheses: "everyone in department 1, or the second-year students of department 2." The tree on the right is our intent: "department 1 or 2, and second year." You put the part you want to happen first in parentheses; what is inside parentheses is always evaluated first.
Which students does this condition select?
SELECT first_name, last_name FROM student WHERE department_id = 1 OR department_id = 2 AND year = 2;
Example 4: OR with parentheses. The committee's third list:
SELECT first_name, last_name, department_id, year FROM student WHERE (department_id = 1 OR department_id = 2) AND year = 2;
| first_name | last_name | department_id | year |
|---|---|---|---|
| Priya | Novak | 2 | 2 |
| Kenji | Park | 1 | 2 |
| Lucas | Okafor | 1 | 2 |
| Greta | Costa | 2 | 2 |
(4 of 15 rows)
If you remove the parentheses and run SELECT COUNT(*) FROM student WHERE department_id = 1 OR department_id = 2 AND year = 2;, you get 21. The 6 extra rows are the students of department 1 who are not in the second year: the condition without parentheses never applied the year requirement to them. Now build the query yourself.
Put the lines of the query that brings the second-year students of department 1 or 2 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
Using parentheses in mixed conditions is a good habit even where they are not needed. has_scholarship AND (gpa < 2.5) and has_scholarship AND gpa < 2.5 give the same result; but if AND and OR appear in the same condition, parentheses tell everyone who reads the query (including you a week later) your intent clearly.
If a query ran without an error, you only know that its syntax is right; you do not know that its meaning is right. After every filter, look at the row count and ask yourself: "is this number reasonable?" You may have a rough expectation for the scholarship students in Port Alder: there are 45 students in Port Alder, so the result cannot be more than 45. If a query where you added AND brings more rows than before you added it, something is wrong. If more rows come back than you expected, pick a row from the list and read the condition by hand for that row: "is this student really in the second year? Then why is the student in the list?" In the version of Example 4 without parentheses, you would see a first-year student from department 1; when you read the condition for that student, the mistake shows up right away.
Two more small rules will help you. First, the column in the condition does not have to appear in the result. SELECT first_name, last_name FROM student WHERE city = 'Port Alder' AND has_scholarship; does not show the city and scholarship columns but filters the rows by them. If these columns are not needed in the list that goes to the committee, you do not write them. While checking, though, temporarily adding the columns in the condition to SELECT is the easiest way to see why each row is in the list.
Second, an alias you gave in SELECT in lesson 3 does not work in WHERE. SELECT gpa * 25 AS gpa_100 FROM student WHERE gpa_100 > 80; gives an error: column "gpa_100" does not exist. Instead, you write the calculation again in the condition: WHERE gpa * 25 > 80. You will see why this is so in lesson 9, when you learn the order in which a query runs.
SELECT first_name, last_name, gpa FROM student WHERE gpa * 25 > 80;
| first_name | last_name | gpa |
|---|---|---|
| Anika | Park | 3.65 |
| Anika | Rivera | 3.88 |
| Liam | Petrov | 3.5 |
(3 of 19 rows)
The condition is calculated for every row: 3.65 × 25 = 91.25, which is greater than 80, so the row stays. The calculation was done only in the condition; the table did not change.
The same rules apply in every table. Remember the gym's member table from lesson 2:
| member_no | first_name | last_name | phone | plan | age | active |
|---|---|---|---|---|---|---|
| 101 | Sam | Carter | 555 0111 | annual | 22 | true |
| 102 | Sam | Carter | NULL | monthly | 19 | true |
| 103 | Emma | Reed | 555 0122 | monthly | 16 | false |
| 104 | Jake | Miller | 555 0133 | annual | 17 | true |
| 105 | Nora | Diaz |
For a new campaign, the gym manager wants "members with a monthly or annual plan who are 18 or older". The first attempt is written without parentheses:
Example 5: Campaign list.
SELECT first_name, age FROM member WHERE plan = 'monthly' OR plan = 'annual' AND age >= 18;
| first_name | age |
|---|---|
| Sam | 22 |
| Sam | 19 |
| Emma | 16 |
(3 rows)
In the query above without parentheses, why did 16-year-old Emma, who has a monthly plan, get into the list?
WHERE plan = 'monthly' OR plan = 'annual' AND age >= 18
When you write your intent with parentheses, the result changes:
SELECT first_name, age FROM member WHERE (plan = 'monthly' OR plan = 'annual') AND age >= 18;
| first_name | age |
|---|---|
| Sam | 22 |
| Sam | 19 |
(2 rows)
Both queries ran without an error. The difference is only in the meaning: one put a 16-year-old member in the adult campaign. Because this table has 5 rows, you saw the mistake by eye; in a member table with 5,000 rows, you can catch it only by looking at the row count and reading a row by hand.
The president's office wants the departments that were founded before 2000 or that belong to the Faculty of Engineering. Here "or" really means OR:
SELECT name, founded_year, faculty FROM department WHERE founded_year < 2000 OR faculty = 'Faculty of Engineering';
| name | founded_year | faculty |
|---|---|---|
| Software Engineering | 2012 | Faculty of Engineering |
| Industrial Engineering | 1999 | Faculty of Engineering |
| Business Administration | 1999 | Faculty of Business and Management |
| Data Science and Analytics | 2026 | Faculty of Engineering |
(4 rows)
Industrial Engineering meets both conditions but comes only once: OR keeps or throws away a row, it does not count it twice. If you had written AND instead of
Mixing AND and OR without parentheses. If you remove the parentheses in Example 4, the query does not give an error but returns 21 rows instead of 15: because AND is evaluated first, all the years of department 1 get into the result. PostgreSQL not giving an error does not mean the result is right. If AND and OR appear in the same condition, write your intent clearly with parentheses, then look at the row count and read a row by hand.
WHERE checks the condition separately for each row and keeps the ones where it is true; numbers are written without quotes, text and dates in single quotes (dates as year-month-day), and text comparison is done letter by letter.AND needs both conditions, OR needs at least one, and NOT reverses a condition; an "and" in English often means OR, so try the condition on a single row.AND is evaluated before OR; if both appear together, write your intent with parentheses and check the result with the row count.Next lesson: You will shorten long OR chains with IN, ranges with BETWEEN, and patterns with LIKE.
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.
| student |
| 20 |
| true |
ORAdding a third requirement to the list in Example 3 makes the result smaller:
SELECT first_name, last_name, gpa FROM student WHERE has_scholarship AND gpa < 2.5 AND year = 4;
| first_name | last_name | gpa |
|---|---|---|
| Ivan | Costa | 1.75 |
| Adaeze | Álvarez | 0.14 |
| Aisha | Nguyen | 1.46 |
(3 rows)
A condition made only of AND needs no parentheses: in whatever order they combine, all three requirements must be true. Going from 15 rows down to 3 is the expected direction.