skip to content

filtering with WHERE

comparisons, AND, OR, NOT, BETWEEN and IN. and the missing parentheses around an OR.

address
everything.basics.filtering_rows
part
part 2, one table
chapter
chapter 2 of 12
reading time
7 min

WHERE asks every row the same question, one row at a time, and keeps the rows where the answer is true. comparisons, AND, OR, NOT, BETWEEN and IN are how you write the question.

AND binds tighter than OR, so a OR b AND c means a OR (b AND c). put parentheses around every OR you mix with an AND.

the picture

you know how WHERE feels like searching? it isn't, really. postgres doesn't go looking for the matching rows. it takes every row FROM hands over, asks it your question, and keeps the ones that say yes.

think of a bouncer with a checklist. one person at a time walks up, the bouncer ticks through the list for that person alone, and it's in or out. the bouncer never compares two people, never remembers the last one, and never lets in a "maybe".

query.sqlstep 1: FROM
  1. 1SELECT code, title
  2. 2FROM courses
  3. 3WHERE credits = 4 AND dept <> 'CS'
  4. 4ORDER BY code;
the table after FROM
codetextdepttextcreditsint2titletext
MATH101MATH4Calculus I
PHYS101PHYS4Mechanics
PHYS201PHYS4Electromagnetism
CS101CS4Intro to Programming
CS201CS4Data Structures
CS301CS4Databases
CS350CS4Operating Systems
CS401CS4Database Internals
CS499GEN6Senior Thesis
HIST101HIST3History of Computing
MATH201MATH3Discrete Math
MATH301MATH3Linear Algebra
(12 rows)

FROM hands over all 12 courses, drawn with the three that will survive on top, so you can watch the other 9 go.

the query that produced this table
SELECT code, dept, credits, title FROM courses ORDER BY (credits = 4 AND dept <> 'CS') DESC, code
clause 1/3
real output, postgres 18.6 (PGlite 0.5.12) · filtering-rows
step through it. WHERE asks each of the 12 courses whether it has 4 credits and isn't CS, on its own, and strikes the 9 that say no. dept and credits are dropped at SELECT: a column can filter without being shown.

the plan says the same thing in its own words: a scan that reads every row and a filter that throws most of them away.

sqldb=school
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF, SUMMARY OFF)
SELECT code, title FROM courses WHERE credits = 4 AND dept <> 'CS';
output, from postgres 18.6
EXPLAIN
Seq Scan on courses (actual rows=3.00 loops=1) Filter: ((dept <> 'CS'::text) AND (credits = 4)) Rows Removed by Filter: 9

Rows Removed by Filter: 9, the same 9 the stepper struck. on a big table, an index lets postgres skip the rows that can't match instead of asking them all, but the answer has to come out the same: WHERE's meaning is "every row, asked one by one", however it's carried out.

comparisons

the six comparison operators work on anything that can be ordered: numbers, text, dates, timestamps.

operatormeans
=equal
<> or !=not equal (the same operator, two spellings)
< <= > >=less, at most, greater, at least

each one gives back a boolean, and WHERE wants exactly that. mysql and sqlite let WHERE 1 mean "every row", because to them a number can be true. postgres won't guess:

sqldb=school
SELECT name FROM students WHERE 1;
output, from postgres 18.6
ERROR 42804: argument of WHERE must be type boolean, not type integer
1 │ SELECT name FROM students WHERE 1;
at line 1, column 33

WHERE true is the postgres spelling, if you ever need it. and comparing text compares it exactly, capitals included, in the byte order of the C collation this page runs: 'Zoe' < 'a' is true here. LIKE, ILIKE and regular expressions is the chapter about matching text more loosely.

AND, OR and NOT

AND needs both sides true, OR needs one, NOT flips. when you mix them, they don't apply left to right: NOT goes first, then AND, then OR, just like * before + in arithmetic.

predict the output
sql
SELECT code, dept, credits
FROM courses
WHERE dept = 'CS' OR dept = 'MATH' AND credits = 3;

here's how postgres reads it, and how you probably meant it:

as written: a OR b AND c
  • ├── dept = 'CS'
  • └──
  • ├── dept = 'MATH'
  • └── credits = 3
as meant: (a OR b) AND c
  • ├──
  • │ ├── dept = 'CS'
  • │ └── dept = 'MATH'
  • └── credits = 3
the same three comparisons, grouped two ways. without parentheses, AND takes dept = 'MATH' and credits = 3 together first, and the OR is on top.

and what each one returns:

parentheses =
query.sql
  1. 1SELECT code, dept, credits
  2. 2FROM courses
  3. 3WHERE dept = 'CS' OR dept = 'MATH' AND credits = 3
  4. 4ORDER BY code;
the result for none
codetextdepttextcreditsint2
CS101CS4
CS201CS4
CS301CS4
CS350CS4
CS401CS4
MATH201MATH3
MATH301MATH3
(7 rows)

without parentheses, AND goes first: every CS course, plus the MATH courses with 3 credits. seven rows.

real output, postgres 18.6 (PGlite 0.5.12) · filtering-rows
switch the parentheses on. seven rows become two: with the OR grouped first, the credits test applies to CS too, and no CS course has 3 credits.

no error, no warning, and the wrong query returns plausible rows. that's what makes it dangerous. the habit that saves you: every time an OR sits next to an AND, put parentheses around the OR, even when you're sure.

BETWEEN and IN

x BETWEEN a AND b is shorthand for x >= a AND x <= b. both ends are included:

sqldb=shop
SELECT name, price
FROM products
WHERE price BETWEEN 19.99 AND 24.00
ORDER BY price, id;
output, from postgres 18.6
SELECT 11
nametextpricenumeric
left-handed teapot19.99
pro chew toy20.66
linen yo-yo21.03
smart cutting board21.48
spare grater21.55
heavy desk lamp21.74
classic monitor stand22.35
small binder22.81
bamboo stapler23.74
classic soap dish23.90
wooden train24.00
(11 rows)

the teapot at exactly 19.99 and the wooden train at exactly 24.00 both make it. NOT BETWEEN is everything outside, ends excluded.

x IN (a, b, c) is shorthand for x = a OR x = b OR x = c, and reads a lot better:

sqldb=school
SELECT code, dept, credits
FROM courses
WHERE dept IN ('MATH', 'PHYS')
ORDER BY code;
output, from postgres 18.6
SELECT 5
codetextdepttextcreditsint2
MATH101MATH4
MATH201MATH3
MATH301MATH3
PHYS101PHYS4
PHYS201PHYS4
(5 rows)

its opposite, NOT IN, has one nasty edge: a NULL in the list makes it return no rows at all. NULL and three-valued logic shows why, and the NOT IN trap shows the version that bites in real code.

BETWEEN and the last day of the month

BETWEEN's inclusive end is a trap with timestamps. '2026-01-31' compared with a timestamp means midnight at the start of the 31st, so "BETWEEN january 1st and january 31st" stops before the 31st has begun:

WHERE =
query.sql
  1. SELECT count(*) AS orders
  2. FROM orders
  3. WHERE ordered_at BETWEEN '2026-01-01' AND '2026-01-31';
≤ 2026-01-31 00:00jan 31feb 1the month ends here
orders in january, this way
831
january 31st orders left out
28

BETWEEN '2026-01-01' AND '2026-01-31' means up to and including 2026-01-31 00:00:00. every order placed later that day is out, and nothing tells you.

inside the rangejanuary, but left outfebruary
real output, postgres 18.6 (PGlite 0.5.12) · filtering-rows-shop
every order around the end of january, one tick each. pick the range. BETWEEN stops at 00:00 on the 31st, so the whole last day is left out. the half-open range runs up to, not including, 00:00 on february 1st.

831 orders one way, 859 the other: a whole day of orders gone from a monthly report, with nothing to tell you. write time ranges half-open, >= the start and < the next start, and the boundaries take care of themselves. the time zone matters too: these midnights are UTC, the zone this page runs in (timestamptz).

keylines

  • WHERE asks each row the same question on its own, and keeps only the rows that say true.
  • comparisons give booleans. postgres won't treat 1 as true.
  • NOT, then AND, then OR. put parentheses around an OR that sits next to an AND.
  • BETWEEN includes both ends. IN is a row of ORs; NOT IN breaks on a NULL.
  • for time ranges, use >= start AND < next start, never BETWEEN.