WHERE Filters
Keep only the rows you want with WHERE, combine tests with AND, OR and NOT, and read the order they run in.
WHERE is a test for every row
WHERE runs a test on each row of the table. A row stays in the result only when the test is TRUE. Rows where the test is FALSE or unknown are dropped.
The comparison operators are =, <> (not equal), <, >, <= and >=. You can also write !=, which PostgreSQL turns into <>.
AND, OR and NOT combine tests. AND needs both sides to be true. OR needs at least one. NOT flips true and false.
Filter inside the database
A table can hold millions of rows. Asking the database for only the matching ones is much faster than loading everything and filtering in your program.
It also keeps the rule in one place: the query says exactly which rows count.
Combine tests, and know what runs first
Keep the Red players who scored over 20, plus every Blue player:
SELECT name, team, points
FROM players
WHERE team = 'Red' AND points > 20
OR team = 'Blue';SQL runs NOT first, then AND, then OR. So this means (team = 'Red' AND points > 20) OR team = 'Blue'. Brackets change the order: team = 'Red' AND (points > 20 OR team = 'Blue') keeps only Red players, because a player cannot be Red and Blue at once.
When you are not sure, add brackets. They cost nothing and make the meaning clear to the next reader.
Read TRUE, FALSE or UNKNOWN for every row
Pick a WHERE condition. The WHERE column shows the test result for each player, and only TRUE rows reach the result.
| nametext | teamtext | pointsinteger | WHERE |
|---|---|---|---|
| Asha | Red | 31 | TRUE |
| Ben | Blue | 17 | FALSE |
| Chen | Red | NULL | UNKNOWN |
| Dara | Green | 24 | TRUE |
| Eli | Blue | NULL | UNKNOWN |
| Fay | Red | 24 | TRUE |
| Gus | Green | 40 | TRUE |
| Hana | Blue | 17 | FALSE |
| nametext | teamtext | pointsinteger |
|---|---|---|
| Asha | Red | 31 |
| Dara | Green | 24 |
| Fay | Red | 24 |
| Gus | Green | 40 |
A comparison keeps the rows where it is TRUE. Chen and Eli have no points, so the test is UNKNOWN and they are dropped.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- WHERE keeps a row only when its test is TRUE, so FALSE and unknown rows are both dropped.
- NOT runs first, then AND, then OR. Brackets override the order.
- A comparison with NULL is unknown, so
<>and=never keep a NULL row. - When mixing AND and OR, add brackets so the meaning is obvious.
Done with this concept?
Mark it complete to track your progress. No login needed.