TExcelTAD
Home › PostgreSQL › PostgreSQL IN & BETWEEN

PostgreSQL IN & BETWEEN

Two operators make common WHERE clauses shorter and easier to read: IN tests whether a value is in a list, and BETWEEN tests whether it lies within a range.

IN: one of several values

Instead of chaining OR conditions:

text
WHERE country = 'UK' OR country = 'Ireland' OR country = 'France'

write a list:

pgsql · try it yourself
SELECT first_name, last_name, country
FROM customers
WHERE country IN ('UK', 'Ireland', 'France')
ORDER BY country, first_name;
 first_name | last_name | country
------------+-----------+---------
 Chloé      | Dubois    | France
 Liam       | O'Brien   | Ireland
 Ben        | Carter    | UK
 Isla       | Murray    | UK
 Olivia     | Martin    | UK
(5 rows)

NOT IN keeps everything except the listed values:

pgsql · try it yourself
SELECT id, status FROM orders
WHERE status NOT IN ('delivered', 'cancelled')
ORDER BY id;
 id | status
----+---------
 16 | shipped
 17 | shipped
 18 | pending
 19 | pending
(4 rows)

IN with a subquery

The list can come from a query. Books that have been ordered at least once:

pgsql · try it yourself
SELECT id, title
FROM books
WHERE id IN (SELECT book_id FROM order_items)
  AND category_id = 1;
 id |       title
----+-------------------
  1 | The Salt Road
 15 | Paper Lanterns
 20 | Starlight Kitchen
(3 rows)

The NOT IN and NULL trap

If the list contains a NULL, NOT IN can never be true, because "x is not equal to unknown" is unknown. The query silently returns no rows:

pgsql · try it yourself
SELECT count(*) AS normal FROM authors WHERE birth_year NOT IN (1959, 1962);
SELECT count(*) AS with_null FROM customers WHERE id NOT IN (1, 2, NULL);
 normal
--------
      7
(1 row)

 with_null
-----------
         0
(1 row)

The first query skips the author with the unknown birth year (NULL in the column), and the second returns 0: customer 3 is clearly not 1 or 2, but nobody can say whether 3 equals the unknown value, so no row qualifies. When a subquery might return NULLs, use NOT EXISTS instead (see EXISTS, ANY & ALL).

BETWEEN: a range

x BETWEEN a AND b means x >= a AND x <= b. Both ends are included:

pgsql · try it yourself
SELECT title, price
FROM books
WHERE price BETWEEN 12.50 AND 15.00
ORDER BY price;
       title       | price
-------------------+-------
 Harbor Lights     | 12.50
 The Map Thief     | 12.99
 The Quiet Witness | 13.49
 Starlight Kitchen | 13.75
 The Salt Road     | 14.99
(5 rows)

Dates with BETWEEN

BETWEEN is popular for date ranges. Orders placed in the second quarter of 2024:

pgsql · try it yourself
SELECT id, order_date
FROM orders
WHERE order_date BETWEEN '2024-04-01' AND '2024-06-30'
ORDER BY order_date;
 id | order_date
----+------------
  7 | 2024-04-08
  8 | 2024-04-27
  9 | 2024-05-15
 10 | 2024-06-01
 11 | 2024-06-22
(5 rows)

Note: On timestamp columns, BETWEEN '2024-04-01' AND '2024-06-30' stops at midnight at the start of June 30 and misses the rest of that day. For timestamps prefer a half-open range: ts >= '2024-04-01' AND ts < '2024-07-01'.

NOT BETWEEN and text ranges

NOT BETWEEN selects values outside the range. On text, ranges follow the sort order:

pgsql · try it yourself
SELECT last_name FROM customers
WHERE last_name BETWEEN 'C' AND 'F'
ORDER BY last_name;

SELECT name, salary FROM employees
WHERE salary NOT BETWEEN 3000 AND 6000
ORDER BY salary;
 last_name
-----------
 Carter
 Dubois
(2 rows)

     name      | salary
---------------+---------
 Tim Novak     | 2900.00
 Victor Chen   | 6200.00
 Nadia Hussein | 6400.00
 Rachel Adams  | 9500.00
(4 rows)

"Fischer" is missing from the first result: it sorts after the single letter 'F'. Text ranges are easy to get wrong; last_name >= 'C' AND last_name < 'G' says what you mean.

Test yourself

Is 20 included in x BETWEEN 10 AND 20?

  1. Yes, both ends are inclusive
  2. No, the upper end is excluded
  3. Only for integers
  4. Only with ORDER BY

What does WHERE 5 NOT IN (1, 2, NULL) return?

  1. true
  2. false
  3. NULL, so the row is filtered out
  4. An error

Which is the same as status IN ('pending', 'shipped')?

  1. status = 'pending' AND status = 'shipped'
  2. status = 'pending' OR status = 'shipped'
  3. status BETWEEN 'pending' AND 'shipped'
  4. status LIKE 'pending%shipped'