SELECT and WHERE
- Version
- 19
- Review
- Draft
Summary#
SELECT chooses the output columns and WHERE keeps only the rows whose condition is true. A condition that is false or null removes the row.
Syntax#
SELECT column_list
FROM table_name
WHERE condition
ORDER BY column_name;
value IS NULL
value IS DISTINCT FROM other_value
value BETWEEN low AND high
value IN (first_value, second_value)
text_column ILIKE pattern
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE books (
id integer PRIMARY KEY,
title text NOT NULL,
price numeric(6,2) NOT NULL,
published integer
);
INSERT INTO books (id, title, price, published) VALUES
(1, 'Atlas of Rivers', 18.50, 2019),
(2, 'Binary Gardens', 32.00, 2024),
(3, 'Cold Harbor', 22.00, NULL),
(4, 'Desert Radio', 24.75, 2022);
-- AND binds tighter than OR, so the parentheses matter.
SELECT title, price
FROM books
WHERE price BETWEEN 15 AND 30
AND (published >= 2020 OR published IS NULL)
ORDER BY id;
SELECT title
FROM books
WHERE title ILIKE '%ar%'
AND id IN (1, 2, 3)
ORDER BY id;
SELECT count(*) FILTER (WHERE published <> 2024) AS using_not_equal,
count(*) FILTER (WHERE published IS DISTINCT FROM 2024) AS using_distinct
FROM books;
ROLLBACK;
Expected output#
title|price
Cold Harbor|22.00
Desert Radio|24.75
(2 rows)
title
Binary Gardens
Cold Harbor
(2 rows)
using_not_equal|using_distinct
2|3
(1 row)
Common mistakes#
Ordinary comparisons such as column = NULL yield unknown. Use IS NULL to test for null, and IS DISTINCT FROM when null should count as different from a value. If the subquery returns a null, x NOT IN (subquery) can only be false or unknown. Use a correlated NOT EXISTS for an anti-join, and add x IS NOT NULL if null values on the left should also be excluded.
Version applicability#
The example's aggregate FILTER requires PostgreSQL 9.4. ILIKE is a PostgreSQL extension, so other database systems may not accept it.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0