Filtering Rows with WHERE

A WHERE clause keeps rows whose condition evaluates to true. Good examples include cases on both sides and at the threshold.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a selection
  2. Check an unknown comparison
  3. Explain why null falls outside an ordinary threshold
  4. Include absence deliberately if the report requires it

Trace a selection

A query for quantity at least five keeps rows with values five and seven and leaves out four. Inclusive comparison boundaries explain that threshold.

Check an unknown comparison

If quantity is null, comparing it to five yields unknown in standard SQL behavior. That row is not kept by this condition. An explicit null rule can include or label it when intended. See three-valued logic.[1]

Explain why null falls outside an ordinary threshold

For quantities four, five, seven and null, the filter qty >= 5 includes five and seven. Four yields false and null yields unknown. A WHERE clause keeps rows whose condition is true. See inclusive comparison boundaries.

WITH samples(id, qty) AS (VALUES (1,4), (2,5), (3,7), (4,NULL))
SELECT id, qty FROM samples WHERE qty >= 5 ORDER BY id;
-- Expected IDs: 2, 3.

Include absence deliberately if the report requires it

To show unmeasured rows as well, a predicate can have an explicit null branch. Do not convert null to zero unless the domain permits it. Test exact threshold, just below and missing.

References

  1. PostgreSQL Global Development Group, Queries ↩