Brainlag
  1. Library
  2. Concepts
  3. SQL

Filtering rows with WHERE

WHERE keeps only the rows that pass a test. Combine tests with AND and OR, and match patterns, lists and ranges with LIKE, IN and BETWEEN.

SQL10 min

Keep the rows that pass

WHERE goes after FROM and tests every row. Rows where the test is true stay; the rest are dropped.

SQL
SELECT title, year
FROM songs
WHERE year >= 2023;

Comparisons: =, != (or <>), <, >, <=, >=. Text goes in single quotes, WHERE genre = 'pop', and = on text is exact: 'Pop' and 'pop' are different values.

Combine tests and match patterns

  • AND needs both tests true. OR needs at least one.
  • AND is worked out before OR, like times before plus in maths. a OR b AND c means a OR (b AND c). When you mix them, add brackets.
  • LIKE matches a pattern: % is any run of characters, _ is exactly one. title LIKE '%hour%' finds "Golden Hour" and "Blue Hour" (in SQLite, LIKE ignores case for English letters).
  • IN (...) is a short way to write several = joined by OR: country IN ('UK', 'US').
  • BETWEEN a AND b includes both ends: year BETWEEN 2020 AND 2022 keeps 2020, 2021 and 2022.

Run it: mid-length songs from two years

Run it, then change one thing and run it again.

Tables artists, songs, listeners, plays
artists 8 rows, 4 columns
idnamecountrygenre
1Nova LaneUKpop
2The TidewaterUSindie
3Kaito MoriJPelectronic
4Amara OseiGHafrobeats
5Lumen ChoirSEpop
6Rust & VelvetUKrock
7Pixel HeartsKRpop
8Juno BayAUindie
songs 30 rows, 5 columns
idtitleartist_idsecondsyear
1Neon Rain61782022
2Slow Motion11582025
3Paper Planes22332023
4Static12692020
5Golden Hour11622022
6Night Bus71572020
7Echoes22812022
8Sugar Rush12842019
9Low Tide42892019
10Glass House71522020
11Satellite12822025
12Wildfire32142022

First 12 of 30 rows. Query the table to see the rest.

listeners 10 rows, 4 columns
idusernameagecountry
1maya_k15UK
2devraj17IN
3lucia.p16ES
4tom_h14UK
5ana.s18BR
6kenji16JP
7zoe_r15US
8femi17NG
9liv13SE
10oscar.b16NULL
plays 70 rows, 5 columns
idlistener_idsong_iddayskipped
110162026-09-010
2832026-09-010
35162026-09-010
4222026-09-010
55212026-09-010
65232026-09-020
7612026-09-020
8662026-09-020
9822026-09-021
10552026-09-020
117132026-09-020
12262026-09-030

First 12 of 70 rows. Query the table to see the rest.

query.sql to run
SELECT title, year, seconds
FROM songs
WHERE year IN (2022, 2023)
  AND seconds BETWEEN 180 AND 240
  AND title NOT LIKE 'The %'
ORDER BY year, title;

A UK artist on the world playlist

A playlist editor wants the name and country of every pop or indie artist from outside the UK. Nova Lane, who is from the UK, keeps showing up. Fix the query.

exercise_1.sql to run
SELECT name, country
FROM artists
WHERE genre = 'pop' OR genre = 'indie' AND country != 'UK';

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.