Database Queries: A First Look at SQL · Lesson 27 of 112

Database WHERE: Choosing Rows

What you will learn

  • How WHERE filters rows
  • Comparison operators, AND, OR, BETWEEN, IN and LIKE
  • Why NULL needs IS NULL

This lesson runs on the sample database you chose in lesson 4.1. Use the Example data picker at the top to change it; every example below changes with it.

1. WHERE

SELECT chooses columns; WHERE chooses rows. Only rows for which the condition is true are kept. (Each query ends with LIMIT 5 to keep the result short; lesson 4.3 explains it.)

SELECT name, price FROM products WHERE price > 40 ORDER BY price LIMIT 5;
name         price
-----------  -----
Plant pot     42.9
Ceramic mug   44.1
Bookshelf     49.0
Drawing kit   53.9
Tea kettle    79.0
(5 rows)
SELECT txn_id, kind, amount_cents FROM transactions WHERE amount_cents > 50000 LIMIT 5;
txn_id  kind     amount_cents
------  -------  ------------
     1  deposit         54800
     2  deposit         53200
     3  deposit         76000
    16  deposit         59500
    28  deposit         52500
(5 rows)
SELECT code, title, credits FROM courses WHERE credits >= 4 LIMIT 5;
code     title                   credits
-------  ----------------------  -------
MATH101  Foundations of Algebra        4
MATH301  Statistics                    4
SCI101   General Science               4
SCI201   Chemistry                     4
SCI202   Physics                       4
(5 rows)

The comparison operators are =, <> (not equal), <, >, <= and >=. Note that SQL uses a single = to compare, and text goes in single quotes:

SELECT first_name, last_name FROM customers WHERE city = 'Dhaka' LIMIT 5;
first_name  last_name
----------  ---------
Elena       Kumar
Bela        Kamau
Anil        Costa
Bruno       Meyer
Rina        Park
(5 rows)
SELECT account_id, account_type, status FROM accounts WHERE account_type = 'savings' LIMIT 5;
account_id  account_type  status
----------  ------------  ------
         2  savings       open
         3  savings       open
         7  savings       closed
         8  savings       open
         9  savings       open
(5 rows)
SELECT section_id, course_id, term FROM sections WHERE term = '2026-Spring' LIMIT 5;
section_id  course_id  term
----------  ---------  -----------
         4          2  2026-Spring
        14          7  2026-Spring
        19          9  2026-Spring
        22         10  2026-Spring
        25         11  2026-Spring
(5 rows)

2. AND and OR

AND needs both conditions true; OR needs at least one.

SELECT name, price, is_active FROM products WHERE is_active = 1 AND price < 10 LIMIT 5;
SELECT name, price, stock FROM products WHERE price < 5 OR stock = 0 LIMIT 5;
name          price  is_active
------------  -----  ---------
Steel pan       6.6          1
Glass jar       5.4          1
Sticky notes   7.65          1
Wall planner    6.6          1
Footrest       4.95          1
(5 rows)

name              price  stock
----------------  -----  -----
Steel pan           6.6      0
Wooden spoon set   29.5      0
Garden gloves      39.0      0
Gel pens (10)      24.0      0
Wall planner        6.6      0
(5 rows)
SELECT txn_id, kind, amount_cents FROM transactions WHERE kind = 'withdrawal' AND amount_cents > 20000 LIMIT 5;
SELECT txn_id, kind, amount_cents FROM transactions WHERE kind = 'fee' OR kind = 'interest' LIMIT 5;
txn_id  kind        amount_cents
------  ----------  ------------
     4  withdrawal         23900
    35  withdrawal         22100
    38  withdrawal         27700
    39  withdrawal         21600
    41  withdrawal         29200
(5 rows)

txn_id  kind  amount_cents
------  ----  ------------
     5  fee           1000
     7  fee            500
    14  fee           1000
    42  fee            200
    43  fee            200
(5 rows)
SELECT code, title, credits FROM courses WHERE credits = 4 AND department_id = 6;
SELECT code, title, credits FROM courses WHERE department_id = 1 OR credits = 2;
code   title        credits
-----  -----------  -------
CS201  Programming        4
CS301  Databases          4
(2 rows)

code     title                   credits
-------  ----------------------  -------
MATH101  Foundations of Algebra        4
MATH201  Geometry                      3
MATH301  Statistics                    4
LANG102  Reading Circle                2
HUM301   Civics                        2
ART101   Drawing                       2
ART201   Music                         2
ART202   Drama                         2
(8 rows)

Mix them with care and use brackets, as in maths: WHERE (a OR b) AND c.

3. BETWEEN, IN and LIKE

These are shortcuts for common tests.

SELECT name, price FROM products WHERE price BETWEEN 10 AND 20 ORDER BY price LIMIT 5;
SELECT order_id, status FROM orders WHERE status IN ('paid', 'shipped') LIMIT 5;
SELECT name FROM products WHERE name LIKE '%mug%';
name            price
--------------  -----
Hand weights     10.8
Yoga mat         12.0
Board game       12.0
Desk organiser  13.95
Card game       17.05
(5 rows)

order_id  status
--------  -------
       4  paid
       9  shipped
      23  paid
      31  shipped
      32  paid
(5 rows)

name
-----------
Ceramic mug
Camping mug
(2 rows)
SELECT txn_id, kind, amount_cents FROM transactions WHERE amount_cents BETWEEN 10000 AND 20000 LIMIT 5;
SELECT txn_id, kind FROM transactions WHERE kind IN ('deposit', 'interest') LIMIT 5;
SELECT txn_id, description FROM transactions WHERE description LIKE 'Transfer%' LIMIT 5;
txn_id  kind        amount_cents
------  ----------  ------------
    15  deposit            16100
    20  withdrawal         10400
    21  withdrawal         13100
    26  deposit            12600
    27  withdrawal         14000
(5 rows)

txn_id  kind
------  -------
     1  deposit
     2  deposit
     3  deposit
     8  deposit
    10  deposit
(5 rows)

txn_id  description
------  ---------------------------
   889  Transfer 1 to account 130
   890  Transfer 1 from account 276
  1053  Transfer 2 to account 341
  1054  Transfer 2 from account 406
  1275  Transfer 3 to account 227
(5 rows)
SELECT code, title, credits FROM courses WHERE credits BETWEEN 2 AND 3 LIMIT 5;
SELECT section_id, term FROM sections WHERE term IN ('2025-Spring', '2025-Autumn') LIMIT 5;
SELECT code, title FROM courses WHERE title LIKE '%Science%';
code     title            credits
-------  ---------------  -------
MATH201  Geometry               3
SCI301   Biology                3
LANG101  Writing Skills         3
LANG102  Reading Circle         2
LANG201  Second Language        3
(5 rows)

section_id  term
----------  -----------
         1  2025-Autumn
         2  2025-Spring
         3  2025-Autumn
         5  2025-Spring
         6  2025-Autumn
(5 rows)

code    title
------  ---------------
SCI101  General Science
(1 row)
  • BETWEEN a AND b includes both ends.
  • IN (...) means "equal to any of these".
  • LIKE matches patterns: % stands for any run of characters, _ for exactly one. '%mug%' means "contains mug". In SQLite, LIKE ignores upper/lower case for plain English letters; other systems can differ, so check the documentation of the one you use.

4. The NULL trap

NULL means "unknown or missing" (lesson 2.3). Nothing is equal to an unknown value, not even another NULL, so = NULL never matches:

Orders that have not shipped yet have no shipped_on date: it is NULL.

SELECT order_id, status FROM orders WHERE shipped_on = NULL LIMIT 5;
SELECT order_id, status FROM orders WHERE shipped_on IS NULL LIMIT 5;
SELECT order_id, shipped_on FROM orders WHERE shipped_on <> '2026-01-15' LIMIT 5;
order_id  status
--------  ------
(0 rows)

order_id  status
--------  ---------
       4  paid
      15  pending
      16  cancelled
      23  paid
      24  pending
(5 rows)

order_id  shipped_on
--------  ----------
       1  2025-04-24
       2  2024-01-26
       3  2025-05-04
       5  2024-05-27
       6  2026-04-09
(5 rows)

Some rows of the audit log have no note: it is NULL.

SELECT log_id, table_name FROM audit_log WHERE note = NULL LIMIT 5;
SELECT log_id, table_name FROM audit_log WHERE note IS NULL LIMIT 5;
SELECT log_id, note FROM audit_log WHERE note <> 'card replaced' LIMIT 5;
log_id  table_name
------  ----------
(0 rows)

log_id  table_name
------  ----------
     1  cards
     2  accounts
     6  cards
     7  loans
     8  customers
(5 rows)

log_id  note
------  ---------------
     3  limit raised
     4  status changed
     5  status changed
    12  address changed
    14  address changed
(5 rows)

A student's grade is NULL until the teacher has given one.

SELECT student_id, section_id FROM enrollments WHERE grade = NULL LIMIT 5;
SELECT student_id, section_id FROM enrollments WHERE grade IS NULL LIMIT 5;
SELECT student_id, grade FROM enrollments WHERE grade <> 90 LIMIT 5;
student_id  section_id
----------  ----------
(0 rows)

student_id  section_id
----------  ----------
         2           4
       335           4
         8           4
        84           4
       263           4
(5 rows)

student_id  grade
----------  -----
       162   51.5
       161   86.0
       323   77.3
       238   58.1
       249   50.1
(5 rows)

Use IS NULL (or IS NOT NULL) to test for missing values. The first query finds nothing even though rows exist, and the third query leaves out every row with a NULL: the database cannot say that an unknown value is different from the one you named. If you want those rows too, say so: WHERE x <> 'value' OR x IS NULL.

5. NOT, and three kinds of answer

A condition in SQL is not only true or false. When a NULL is involved the answer can be unknown, and WHERE keeps only rows where the answer is true. That is why <> lost the NULL rows. NOT reverses true and false but leaves unknown as unknown, and it combines with the shortcuts from section 3:

SELECT order_id, status FROM orders WHERE status NOT IN ('paid', 'shipped', 'delivered') LIMIT 5;
SELECT name FROM products WHERE name NOT LIKE '%a%' LIMIT 5;
SELECT name, price FROM products WHERE price NOT BETWEEN 5 AND 70 LIMIT 5;
order_id  status
--------  ---------
      15  pending
      16  cancelled
      24  pending
      40  cancelled
      43  cancelled
(5 rows)

name
----------------
Wooden spoon set
Lunch box
Gel pens (10)
Sticky notes
Highlighters
(5 rows)

name          price
------------  -----
Tea kettle     79.0
Highlighters   79.0
Footrest       4.95
Day backpack    4.5
Water bottle   86.9
(5 rows)
SELECT txn_id, kind FROM transactions WHERE kind NOT IN ('deposit', 'withdrawal') LIMIT 5;
SELECT txn_id, description FROM transactions WHERE description NOT LIKE 'Transfer%' LIMIT 5;
SELECT txn_id, amount_cents FROM transactions WHERE amount_cents NOT BETWEEN 1000 AND 90000 LIMIT 5;
txn_id  kind
------  ----
     5  fee
     7  fee
    14  fee
    42  fee
    43  fee
(5 rows)

txn_id  description
------  ---------------
     1  Opening deposit
     2  Opening deposit
     3  Opening deposit
     4  Card payment
     5  Monthly fee
(5 rows)

txn_id  amount_cents
------  ------------
     7           500
    42           200
    43           200
    59           297
    62           500
(5 rows)
SELECT section_id, term FROM sections WHERE term NOT IN ('2025-Spring', '2025-Autumn') LIMIT 5;
SELECT code, title FROM courses WHERE title NOT LIKE '%a%' LIMIT 5;
SELECT code, credits FROM courses WHERE credits NOT BETWEEN 2 AND 3 LIMIT 5;
section_id  term
----------  -----------
         4  2026-Spring
        14  2026-Spring
        19  2026-Spring
        22  2026-Spring
        25  2026-Spring
(5 rows)

code     title
-------  --------------
MATH201  Geometry
SCI201   Chemistry
SCI202   Physics
SCI301   Biology
LANG101  Writing Skills
(5 rows)

code     credits
-------  -------
MATH101        4
MATH301        4
SCI101         4
SCI201         4
SCI202         4
(5 rows)

A worse surprise comes when the list itself contains a NULL, and when you ask "A or not A". (COUNT(*) counts rows; lesson 4.4 explains it.)

SELECT order_id FROM orders WHERE employee_id NOT IN (1, NULL) LIMIT 5;
SELECT COUNT(*) AS all_orders FROM orders;
SELECT COUNT(*) AS a_or_not_a FROM orders WHERE employee_id = 3 OR employee_id <> 3;
order_id
--------
(0 rows)

all_orders
----------
      2600
(1 row)

a_or_not_a
----------
      2279
(1 row)
SELECT log_id FROM audit_log WHERE note NOT IN ('card replaced', NULL) LIMIT 5;
SELECT COUNT(*) AS all_rows FROM audit_log;
SELECT COUNT(*) AS a_or_not_a FROM audit_log WHERE note = 'card replaced' OR note <> 'card replaced';
log_id
------
(0 rows)

all_rows
--------
     120
(1 row)

a_or_not_a
----------
        91
(1 row)
SELECT student_id FROM enrollments WHERE grade NOT IN (90, NULL) LIMIT 5;
SELECT COUNT(*) AS all_rows FROM enrollments;
SELECT COUNT(*) AS a_or_not_a FROM enrollments WHERE grade = 90 OR grade <> 90;
student_id
----------
(0 rows)

all_rows
--------
    1002
(1 row)

a_or_not_a
----------
       809
(1 row)

NOT IN (..., NULL) returns nothing at all, because for every value the database cannot rule out that it equals the unknown one. This bites in real programs when a list comes from a column that contains NULL. The last two queries show that "A or not A" is not always true in SQL: the rows with a NULL satisfy neither side, so the count is smaller than the total. When data can be missing, decide what should happen to the NULL rows and say so in the query.

Worked example: brackets change the answer

AND is applied before OR. These two queries differ only in brackets, and they count different rows.

Products from supplier 3 that are cheap or out of stock:

SELECT COUNT(*) AS with_brackets FROM products WHERE (price < 10 OR stock = 0) AND supplier_id = 3;
SELECT COUNT(*) AS without_brackets FROM products WHERE price < 10 OR stock = 0 AND supplier_id = 3;
with_brackets
-------------
            4
(1 row)

without_brackets
----------------
              12
(1 row)

Without brackets the database reads price < 10 OR (stock = 0 AND supplier_id = 3): every cheap product is counted, whoever supplies it.

Large deposits or interest payments:

SELECT COUNT(*) AS with_brackets FROM transactions WHERE (kind = 'deposit' OR kind = 'interest') AND amount_cents > 20000;
SELECT COUNT(*) AS without_brackets FROM transactions WHERE kind = 'deposit' OR kind = 'interest' AND amount_cents > 20000;
with_brackets
-------------
         2118
(1 row)

without_brackets
----------------
            3107
(1 row)

Without brackets the database reads kind = 'deposit' OR (kind = 'interest' AND amount_cents > 20000): every deposit of any size is counted.

Sections taught in 2025-Spring or with room for 35, that also have a room:

SELECT COUNT(*) AS with_brackets FROM sections WHERE (term = '2025-Spring' OR capacity = 35) AND room IS NOT NULL;
SELECT COUNT(*) AS without_brackets FROM sections WHERE term = '2025-Spring' OR capacity = 35 AND room IS NOT NULL;
with_brackets
-------------
           20
(1 row)

without_brackets
----------------
              23
(1 row)

Without brackets the database reads term = '2025-Spring' OR (capacity = 35 AND room IS NOT NULL): spring sections without a room are counted too.

The two counts are different because the queries ask different questions. (All data is made up.)

Common mistakes

  • Writing = NULL. It never matches; use IS NULL.
  • Using double quotes for text. Use single quotes: 'Dhaka'.
  • Forgetting that AND binds tighter than OR. Use brackets.
  • Expecting <> 'x' to include unknown values. Rows with NULL are left out.
  • Using NOT IN with a list that may contain NULL. The result can be empty.
  • Spelling the text differently. 'dhaka' and 'Dhaka' are different values when compared with = (lesson 1.1).

Key takeaways

  • WHERE keeps only the rows whose condition is true.
  • Combine conditions with AND, OR and brackets.
  • BETWEEN, IN and LIKE are handy shortcuts.
  • NULL is unknown: test it with IS NULL / IS NOT NULL.
  • A condition can be true, false or unknown; WHERE keeps only the true rows, and NOT does not turn unknown into true.

Practice

1. Write a query for the rows of a table that are above a limit you pick.

Show answer

SELECT name, price FROM products WHERE price >= 45; returns the products that cost 45 or more.

Show answer

SELECT txn_id, amount_cents FROM transactions WHERE amount_cents >= 45000; returns the transactions of 450.00 or more.

Show answer

SELECT code, title FROM courses WHERE credits >= 3; returns the courses worth 3 credits or more.

2. Choose rows whose value is one of two possibilities. Use IN.

Show answer

SELECT order_id FROM orders WHERE status IN ('pending', 'cancelled'); returns the orders that are pending or cancelled.

Show answer

SELECT account_id FROM accounts WHERE status IN ('frozen', 'closed'); returns the accounts that are frozen or closed.

Show answer

SELECT section_id FROM sections WHERE term IN ('2025-Spring', '2026-Spring'); returns the sections of those two terms.

3. Why does WHERE column = NULL return nothing?

Show answer

NULL means unknown, and nothing is equal to an unknown value. Use IS NULL.

4. What does LIKE 'P%' match?

Show answer

Text that starts with P, for example Pen.

5. Write a query for the rows where a column has a value other than one you name, including the rows where it is missing.

Show answer

SELECT order_id FROM orders WHERE shipped_on <> '2026-01-15' OR shipped_on IS NULL; keeps the orders that have not shipped as well.

Show answer

SELECT log_id FROM audit_log WHERE note <> 'card replaced' OR note IS NULL; keeps the rows with no note as well.

Show answer

SELECT student_id FROM enrollments WHERE grade <> 90 OR grade IS NULL; keeps the rows with no grade yet as well.

6. Does BETWEEN 2 AND 5 include 5?

Show answer

Yes, both ends are included.

7. A column contains 'a', 'b' and NULL. Does WHERE x NOT IN ('a') return the row with NULL? What about WHERE x NOT IN ('a', NULL)?

Show answer

No to both. The first leaves the NULL row out because its value is unknown; the second returns no rows at all, because with a NULL in the list the database can never be sure a value is not in it.