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

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

  1. List tasks that are not done.
  2. List tasks with no due date.
  3. List unfinished tasks, most urgent priority first, then by due date.
  4. List tasks whose title contains the word "report".

Answers

  1. SELECT title FROM tasks WHERE done = 0;
  2. SELECT title FROM tasks WHERE due IS NULL;
  3. SELECT title FROM tasks WHERE done = 0 ORDER BY priority, due;
  4. SELECT title FROM tasks WHERE title LIKE '%report%'; Some databases match capital letters differently; in PostgreSQL you can use ILIKE for a case-insensitive match.

Common slips

SlipWhat happensFix
WHERE due = NULLReturns nothingWHERE due IS NULL
Missing brackets with ORMore rows than expectedGroup conditions with brackets
Quotes around numbersUsually works but hides type mistakesLeave numbers unquoted
Forgetting ORDER BYRows appear in an unpredictable orderAlways 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.

Related pages on this site