Sub topic 11
Filtering and sorting results
This chapter shows how to narrow a SELECT to the rows you want and put them in a stable order. It assumes you can connect with psql, that you created firstdb and the books table in earlier chapters, and that you can run a basic SELECT. The chapter covers WHERE, ORDER BY, LIMIT, and the traps around NULL, quoting, and case.
Add two rows to make the examples interesting
The three original books don't show how NULL and ties behave. Connect to firstdb and add two more rows. You will delete them at the end of the chapter.
INSERT INTO books (title, author, published_year)
VALUES
('Dune Messiah', 'Frank Herbert', 1969),
('Untitled Draft', 'Anonymous', NULL);The table now holds five rows. Untitled Draft has no known year, so its published_year is NULL.
How PostgreSQL processes a query
You write SELECT first, but PostgreSQL logically evaluates the clauses in a different order. This explains several behaviors below. For example, WHERE cannot use a column alias that SELECT defines, but ORDER BY can.
Filtering with WHERE
WHERE takes a condition. PostgreSQL keeps a row only when the condition is true for it.
SELECT title, published_year
FROM books
WHERE published_year > 1900
ORDER BY published_year DESC; title | published_year
---------------+----------------
Neuromancer | 1984
Dune Messiah | 1969
Dune | 1965
(3 rows)Emma (1815) fails the condition. Untitled Draft is also missing, and the NULL section below explains why.
Comparison operators
| Operator | Meaning | Example |
|---|---|---|
| `=` | equal | `author = 'Jane Austen'` |
| `<>` or `!=` | not equal | `published_year <> 1965` |
| `<`, `<=`, `>`, `>=` | ordering | `published_year >= 1900` |
| `BETWEEN a AND b` | inclusive range | `published_year BETWEEN 1960 AND 1980` |
| `IN (...)` | matches any listed value | `author IN ('Jane Austen', 'Anonymous')` |
| `LIKE` | pattern match, case-sensitive | `title LIKE 'Dune%'` |
| `ILIKE` | pattern match, case-insensitive (PostgreSQL extension) | `title ILIKE '%dune%'` |
In a LIKE pattern, % matches any run of characters, including none, and _ matches exactly one character. BETWEEN includes both endpoints, so BETWEEN 1960 AND 1980 is the same as >= 1960 AND <= 1980.
Combining conditions
Use AND, OR, and NOT to combine conditions. AND binds tighter than OR, which often surprises people.
-- Reads as: Austen, OR (Gibson AND after 1900)
SELECT title, author
FROM books
WHERE author = 'Jane Austen'
OR author = 'William Gibson' AND published_year > 1900;This returns both Emma and Neuromancer. Emma qualifies because the OR lets any Austen book through. If you meant "either author, but only after 1900", add parentheses:
SELECT title, author
FROM books
WHERE (author = 'Jane Austen' OR author = 'William Gibson')
AND published_year > 1900;This returns only Neuromancer. Use parentheses whenever you mix AND and OR, even when you know the precedence rules. The next reader may not.
NULL is not a value you can compare with =
NULL means "unknown or missing". Any ordinary comparison with NULL produces neither true nor false but NULL, and WHERE keeps only rows where the condition is true. Two consequences follow.
-- Returns zero rows, even though Untitled Draft has no year
SELECT title FROM books WHERE published_year = NULL;
-- Correct
SELECT title FROM books WHERE published_year IS NULL;-- Does NOT return Untitled Draft
SELECT title FROM books WHERE published_year <> 1965;The second query returns Neuromancer, Emma, and Dune Messiah. The draft is excluded because NULL <> 1965 is unknown, not true. To include rows with missing values, say so explicitly:
SELECT title
FROM books
WHERE published_year <> 1965 OR published_year IS NULL;Use IS NULL and IS NOT NULL for these tests. IS DISTINCT FROM treats NULL as an ordinary value, so published_year IS DISTINCT FROM 1965 gives the same result as the query above.
Quoting rules
PostgreSQL uses two kinds of quotes, and they mean different things.
- Single quotes wrap string values:
'Dune'. - Double quotes wrap identifiers such as column and table names:
"title".
SELECT * FROM books WHERE title = "Dune";ERROR: column "Dune" does not exist
LINE 1: SELECT * FROM books WHERE title = "Dune";
^PostgreSQL read "Dune" as a column name. Switch to single quotes. To put a single quote inside a string, double it: 'Ender''s Game'.
String comparison with = is case-sensitive. title = 'dune' matches nothing. Use ILIKE 'dune', or compare lower(title) = 'dune'.
Sorting with ORDER BY
Without ORDER BY, PostgreSQL returns rows in whatever order is convenient. That order can change after an UPDATE, a vacuum, or a different query plan. Never rely on it.
SELECT title, author, published_year
FROM books
ORDER BY author, published_year DESC;Each sort key can have its own direction. The default is ASC (smallest first). DESC reverses it. Here PostgreSQL sorts by author, and rows with the same author are sorted by year, newest first. Frank Herbert's two books come out as Dune Messiah (1969), then Dune (1965).
Where NULLs sort
PostgreSQL treats NULL as larger than any other value. In an ascending sort, NULLs come last. In a descending sort, they come first:
SELECT title, published_year
FROM books
ORDER BY published_year DESC;Untitled Draft appears at the top of this result, which is rarely what you want. Control it with NULLS FIRST or NULLS LAST:
SELECT title, published_year
FROM books
ORDER BY published_year DESC NULLS LAST;Sorting text
Text sorts according to the database's collation, which is a set of language rules. Depending on how the database was created, 'apple' may sort before or after 'Banana'. A C collation sorts by byte value, so uppercase letters come before lowercase. Most Linux and macOS installs default to a language-aware collation, where case matters much less. If a sort looks wrong for your language, check \l in psql. It shows each database's collation columns.
You can also sort by an expression or by a column's position in the select list:
SELECT title, length(title) AS title_length
FROM books
ORDER BY title_length DESC, title;ORDER BY 2 means "sort by the second selected column". It works, but it breaks silently if you reorder the select list, so prefer names or aliases.
Limiting the result
LIMIT caps how many rows come back. Pair it with ORDER BY, because "the first three rows" is only meaningful in a defined order.
-- The two most recent books that have a known year
SELECT title, published_year
FROM books
WHERE published_year IS NOT NULL
ORDER BY published_year DESC
LIMIT 2;OFFSET skips rows first. LIMIT 2 OFFSET 2 returns rows three and four. Large offsets are slow because PostgreSQL still computes and discards the skipped rows. Also, if two rows tie on the sort key, their relative order is not guaranteed. Add a unique column such as id as the last sort key for a deterministic order:
SELECT id, title
FROM books
ORDER BY published_year DESC NULLS LAST, id
LIMIT 2;Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `column "Dune" does not exist` | Double quotes around a string | Use single quotes |
| Zero rows from `= NULL` | `NULL` compared with `=` | Use `IS NULL` |
| Rows with `NULL` vanish after `<>` | Unknown is not true | Add `OR col IS NULL` |
| Too many rows with `OR` | `AND` binds before `OR` | Add parentheses |
| `title = 'dune'` finds nothing | Case-sensitive comparison | Use `ILIKE` or `lower()` |
| Order changes between runs | No `ORDER BY`, or tied sort keys | Sort explicitly and add `id` as a tiebreaker |
| `syntax error at or near "ORDER"` | Clauses out of order | Use `WHERE`, then `ORDER BY`, then `LIMIT` |
Remove the extra rows
Delete the two rows you added, using a WHERE clause so nothing else is touched. Check the filter with a SELECT first.
SELECT id, title FROM books WHERE title IN ('Dune Messiah', 'Untitled Draft');
DELETE FROM books WHERE title IN ('Dune Messiah', 'Untitled Draft');Exercise
Write a query that returns the titles of books whose title starts with "Dune" and that were published after 1966, sorted by title. Using the five-row table from this chapter, what does it return, and why is "Dune" itself missing?
Show answer
SELECT title FROM books WHERE title LIKE 'Dune%' AND publishedyear > 1966 ORDER BY title; It returns only Dune Messiah (1969). Dune matches the pattern, but its year is 1965, which fails publishedyear > 1966.
Exercise
Write a query that lists every book ordered from newest to oldest and puts books with an unknown year at the end.
Show answer
SELECT title, publishedyear FROM books ORDER BY publishedyear DESC NULLS LAST; Without NULLS LAST, a descending sort places NULL values first, because PostgreSQL treats NULL as larger than any other value.