Training Notes: Filtering and Sorting With WHERE and ORDER BY
Most real questions about data are "show me some of it, in a sensible order". WHERE picks the rows, ORDER BY arranges them. These notes cover both, with a practice set at the end.
Objectives
- Filter rows with comparison operators, AND, OR and NOT.
- Match text with LIKE and lists with IN.
- Handle empty values with IS NULL.
- Sort by one or more columns in either direction.
Practice table
CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, priority INTEGER, done INTEGER, due DATE);
INSERT INTO tasks (title, priority, done, due) VALUES
('Buy milk', 2, 0, '2026-12-01'), ('Write report', 1, 0, '2026-11-28'),
('Call bank', 1, 1, NULL), ('Book dentist', 3, 0, NULL);
Here done uses 0 for no and 1 for yes, a common pattern in SQLite.
Filtering with WHERE
SELECT title FROM tasks WHERE priority = 1;
SELECT title FROM tasks WHERE priority <= 2 AND done = 0;
SELECT title FROM tasks WHERE priority = 1 OR due IS NULL;
When you mix AND and OR, add brackets so the meaning is clear:
SELECT title FROM tasks WHERE done = 0 AND (priority = 1 OR due IS NULL);
Text matching. LIKE uses % for "any characters":
SELECT title FROM tasks WHERE title LIKE 'B%';
Lists. IN is shorter than many ORs: WHERE priority IN (1, 2).
Empty values. A missing value is NULL, which means "unknown". You cannot test it with =. Use due IS NULL or due IS NOT NULL.
Sorting with ORDER BY
SELECT title, priority, due FROM tasks ORDER BY priority ASC, due ASC;
Rows are sorted by priority first; ties are broken by due date. Where do NULL due dates go? That depends on the database: some put them first, some last. PostgreSQL lets you say NULLS LAST explicitly.
Practice set
- List tasks that are not done.
- List tasks with no due date.
- List unfinished tasks, most urgent priority first, then by due date.
- List tasks whose title contains the word "report".
Answers
SELECT title FROM tasks WHERE done = 0;SELECT title FROM tasks WHERE due IS NULL;SELECT title FROM tasks WHERE done = 0 ORDER BY priority, due;SELECT title FROM tasks WHERE title LIKE '%report%';Some databases match capital letters differently; in PostgreSQL you can useILIKEfor a case-insensitive match.
Common slips
| Slip | What happens | Fix |
|---|---|---|
WHERE due = NULL | Returns nothing | WHERE due IS NULL |
| Missing brackets with OR | More rows than expected | Group conditions with brackets |
| Quotes around numbers | Usually works but hides type mistakes | Leave numbers unquoted |
| Forgetting ORDER BY | Rows appear in an unpredictable order | Always sort when order matters |
Next
See the same steps drawn as pictures in watching a SELECT query run.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.
This page is a free outline. No downloadable files, paid content, courses or certificates are offered on this site.