Skip to main content

BETWEEN Operator

Editorial

Introduction

A filter often keeps a range: prices from 50 to 200, or the orders of one quarter. BETWEEN says it in one test, and keeps both ends of the range.

Here you will:

  • see how BETWEEN works and that it includes both ends
  • use it with numbers, dates and text
  • compare it with the same test written with >= and <=
  • leave a range out with NOT BETWEEN
  • meet the traps at a range's ends

What is the BETWEEN Operator?

BETWEEN keeps the rows whose value lies inside a range, both ends included.

Syntax

SELECT columns
FROM table_name
WHERE column BETWEEN value1 AND value2;

Key Point: Both Ends Included

BETWEEN 10 AND 20 holds for 10, for 20, and for every value between them, 10.5 and 19.99 too. PostgreSQL's manual says it plainly: "Notice that BETWEEN treats the endpoint values as included in the range."

Basic Example

-- Items priced from 50 to 100, both ends included
SELECT order_id, product_id, price
FROM olist_order_items_dataset
WHERE price BETWEEN 50 AND 100;

33,313 items, among them the 293 priced exactly 50 and the 172 priced exactly 100.

BETWEEN: an inclusive range filter. BETWEEN keeps the lower end, the upper end and every value between. Top left, a number line of prices from 0 to 150 for price BETWEEN 50 AND 100: the range from 50 to 100 lit, both ends drawn closed, and five items of the course's table, the first of each case in the table's stored order: 12.99 left out, 50 kept, 58.9 kept, 100 kept, 145.95 left out. Under it the whole table to scale: 39,024 under 50, 33,313 kept, 40,313 over 100, of 112,650 items; the 293 at exactly 50 and the 172 at 100 are kept too. Included: 50, 58.9 and 100; the ends are part of the result. Excluded: 12.99 and 145.95. Top right, the equivalent SQL: price BETWEEN 50 AND 100 is price >= 50 AND price <= 100, and both keep the same 33,313 items; BETWEEN is inclusive for numbers, dates and text, and SQLite compares text by character code. Bottom left, NOT BETWEEN on the same line: price NOT BETWEEN 50 AND 100 keeps the outside ranges, 79,337 items, 39,024 under 50 and 40,313 over 100; it returns values less than 50 or greater than 100, and because BETWEEN includes its ends, NOT BETWEEN leaves out 50 and 100. Bottom right, the upper end of a range: customer_city BETWEEN 'a' AND 'm' keeps luzilandia and leaves out macae, since names starting with m sort after 'm', 298 of them left out; and BETWEEN '2018-01-01' AND '2018-01-31' stops at 00:00:00 of the bare end date, leaving out the 256 orders of 31 January.

BETWEEN vs Comparison Operators

BETWEEN is a short way to write two comparisons joined by AND. SQLite's manual: "The BETWEEN operator is logically equivalent to a pair of comparisons."

Equivalent Expressions

-- Using BETWEEN
WHERE price BETWEEN 50 AND 100

-- The same with AND
WHERE price >= 50 AND price <= 100

Both keep the same 33,313 items.

When to Use BETWEEN

Use BETWEEN when you want both ends of a range, written once and read at a glance.

Use >= and < when one end must stay out, as when ranges meet or when a range of times ends at a date.

Where BETWEEN Reads Better

WHERE review_score BETWEEN 1 AND 3

-- the same
WHERE review_score >= 1 AND review_score <= 3

Both keep 23,380 reviews.

Where Comparisons Fit Better

-- The upper end left out
WHERE price >= 50 AND price < 100

-- The range and another condition
WHERE price >= 50 AND price <= 100 AND freight_value < 20

The first keeps 33,141 items, the 172 priced exactly 100 left out; the second keeps 25,667.

BETWEEN with Numbers

BETWEEN works with any number column.

Price Ranges

-- Items priced from 0 to 50
SELECT order_id, product_id, price
FROM olist_order_items_dataset
WHERE price BETWEEN 0 AND 50;

39,317 items.

-- Items priced from 50 to 200
SELECT order_id, product_id, price
FROM olist_order_items_dataset
WHERE price BETWEEN 50 AND 200;

60,252 items.

-- Items priced from 200 to 1000
SELECT order_id, product_id, price
FROM olist_order_items_dataset
WHERE price BETWEEN 200 AND 1000;

12,629 items. These three ranges meet at their ends, and BETWEEN takes both ends: the 293 items priced exactly 50 are in the first two ranges, and the 99 priced exactly 200 in the last two. The 844 items over 1000 are in none of them (the dearest costs 6,735). For ranges that meet, write each with >= and <, so that every value lands in exactly one: price >= 50 AND price < 200.

Item Numbers

-- The second to fifth item of each order
SELECT order_id, order_item_id, price
FROM olist_order_items_dataset
WHERE order_item_id BETWEEN 2 AND 5;

13,515 rows. order_item_id numbers an item within its order: 1 for the first item, 2 for the second, up to 21. So this keeps the second to fifth item rows of their orders; it does not find the orders that hold 2 to 5 items, which takes counting each order's items (GROUP BY does that).

Rating Ranges

-- Reviews scored 3 or 4
SELECT order_id, review_score
FROM olist_order_reviews_dataset
WHERE review_score BETWEEN 3 AND 4;

27,487 reviews.

-- Reviews scored 4 or 5
SELECT order_id, review_score
FROM olist_order_reviews_dataset
WHERE review_score BETWEEN 4 AND 5;

76,620 reviews. A review scored 4 is in both ranges.

Payment Installments

-- Payments in 3 to 6 installments
SELECT order_id, payment_type, payment_installments, payment_value
FROM olist_order_payments_dataset
WHERE payment_installments BETWEEN 3 AND 6;

26,718 payments.

BETWEEN with Dates

BETWEEN is handy for ranges of dates. Here the purchase time is text such as '2018-01-31 15:30:00', and text compares character by character, as Comparison Operators shows.

Basic Date Range

-- Orders bought in January 2018, by the date alone
SELECT order_id, order_purchase_timestamp
FROM olist_orders_dataset
WHERE DATE(order_purchase_timestamp) BETWEEN '2018-01-01' AND '2018-01-31';

7,269 orders. DATE(...) cuts each time down to its date, so the whole of 31 January is inside.

Quarter Filtering

-- Orders bought in the first quarter of 2018
SELECT order_id, order_purchase_timestamp
FROM olist_orders_dataset
WHERE order_purchase_timestamp BETWEEN '2018-01-01' AND '2018-03-31 23:59:59';

21,208 orders. Every time here is written to the second, so '2018-03-31 23:59:59' reaches the last one of the quarter.

Year Filtering

-- Orders bought in 2017
SELECT order_id, order_purchase_timestamp
FROM olist_orders_dataset
WHERE order_purchase_timestamp BETWEEN '2017-01-01' AND '2017-12-31 23:59:59';

45,101 orders.

Important: A Bare End Date

A bare date is the first moment of its day:

-- A bare end date: 31 January's times are left out
SELECT COUNT(*) AS orders
FROM olist_orders_dataset
WHERE order_purchase_timestamp BETWEEN '2018-01-01' AND '2018-01-31';

7,013 orders: '2018-01-31 15:30:00' is greater than '2018-01-31', so every time of 31 January after midnight is left out, 256 orders. A range that ends before the next day keeps them, and reads the same for any month:

-- From the first moment of January up to February, left out
SELECT COUNT(*) AS orders
FROM olist_orders_dataset
WHERE order_purchase_timestamp >= '2018-01-01'
  AND order_purchase_timestamp < '2018-02-01';

7,269 orders, as many as DATE(...) gave.

BETWEEN with Text

BETWEEN also works on text. SQLite compares text by the characters' codes, its default way of comparing (BINARY: "Compares string data using memcmp(), regardless of text encoding."), so capitals come before small letters.

Alphabetical Range

-- City names from 'a' to 'm'
SELECT DISTINCT customer_city
FROM olist_customers_dataset
WHERE customer_city BETWEEN 'a' AND 'm';

2,139 of the 4,119 cities. This is not every name from a to m: a name that starts with m and goes on, such as 'macae', is greater than 'm' and lies past the end, so all 298 such names are left out. To keep the names that start with a to m, end the range before 'n':

-- City names that start with a to m
SELECT DISTINCT customer_city
FROM olist_customers_dataset
WHERE customer_city >= 'a' AND customer_city < 'n';

2,437 cities, the 298 starting with m among them.

How Text Comparison Works

Text is compared one character at a time, by code:

  • 'apple' is less than 'banana', because a comes before b
  • 'cat' is less than 'category': a value that ends first comes first
  • 'Zebra' is less than 'apple': capitals come before small letters

Example: State Code Range

-- State codes from 'A' to 'M'
SELECT DISTINCT customer_state
FROM olist_customers_dataset
WHERE customer_state BETWEEN 'A' AND 'M'
ORDER BY customer_state;

AC, AL, AM, AP, BA, CE, DF, ES and GO: the states MA, MG, MS and MT are greater than 'M' and left out.

Practical Use Case

-- Categories that start with a to f
SELECT DISTINCT product_category_name
FROM olist_products_dataset
WHERE product_category_name BETWEEN 'a' AND 'g';

43 categories, each listed once. The range ends at 'g', so it keeps the names that start with a to f. The products with no category are not among them: BETWEEN on a NULL is NULL, so adding AND product_category_name IS NOT NULL changes nothing (18,686 products either way).

Note: for the names that start with some letters, LIKE Operator offers a pattern; BETWEEN on text is a range of codes, ends included.

NOT BETWEEN

NOT BETWEEN keeps the rows whose value lies outside the range.

Syntax

WHERE column NOT BETWEEN value1 AND value2

Example

-- Items priced under 50 or over 200
SELECT order_id, product_id, price
FROM olist_order_items_dataset
WHERE price NOT BETWEEN 50 AND 200;

52,398 items: those priced under 50 and those over 200. The ends belong to BETWEEN, so NOT BETWEEN leaves out an item of exactly 50 or 200.

Equivalent Expression

WHERE price < 50 OR price > 200

NOT Operator shows why the two are the same.

Practical Use Cases

-- Reviews scored 1 or 5
SELECT order_id, review_score
FROM olist_order_reviews_dataset
WHERE review_score NOT BETWEEN 2 AND 4;

69,278 reviews, each scored 1 or 5.

-- Orders bought before 9:00 or from 18:00 on
SELECT order_id, order_purchase_timestamp
FROM olist_orders_dataset
WHERE strftime('%H', order_purchase_timestamp) NOT BETWEEN '09' AND '17';

43,540 orders. The hour comes out of strftime('%H', ...) as two digits of text, so BETWEEN '09' AND '17' holds for every time from 09:00 to 17:59, and NOT keeps the rest.

Common Pitfalls

Pitfall 1: The Ends the Wrong Way Round

The first value must be the smaller one. x BETWEEN 100 AND 50 asks for a value at least 100 and at most 50, and no value is both:

-- The larger value first: no row
SELECT COUNT(*) AS items
FROM olist_order_items_dataset
WHERE price BETWEEN 100 AND 50;

0 items. PostgreSQL has a form that sorts the two ends first: "BETWEEN SYMMETRIC is like BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right." SQLite does not have it:

SELECT 2 BETWEEN SYMMETRIC 3 AND 1;

The site answers near "3": syntax error.

Pitfall 2: Forgetting BETWEEN Is Inclusive

-- To leave both ends out, use comparisons
WHERE price > 50 AND price < 100

-- Not this, which keeps 50 and 100
WHERE price BETWEEN 50 AND 100

Pitfall 3: A Bare End Date

A range of times that ends at a bare date stops at that day's first moment: the January range above lost 256 orders that way. End the range before the next day instead:

WHERE order_purchase_timestamp >= '2018-01-01'
  AND order_purchase_timestamp < '2018-02-01'

Pitfall 4: NULL Values

A NULL is in no range: BETWEEN on a NULL is NULL, and the row is left out.

-- Products weighing from 0 to 50,000 grams
SELECT COUNT(*) AS products
FROM olist_products_dataset
WHERE product_weight_g BETWEEN 0 AND 50000;

32,949 of the 32,951 products. Every weight recorded is at most 40,425 grams, so the 2 left out are the products with no weight.

Try BETWEEN on the course's rows. Pick a table and a condition, then test the rows one at a time or all at once: the chip shows the range's answer, the row's lamp the answer for the whole condition, and only a TRUE row goes through the gate into the result. The items show both ends kept, then left out by NOT BETWEEN, then a range given the wrong way round; the customers show the cities either side of 'm' under both forms; the products show a weight that is NULL.

Five real items, five customers and four products from the course's tables, with each answer as SQLite gives it. Test one row at a time, or every row at once.

Practice

Practice using BETWEEN with different kinds of values.

Exercise 1: Numeric Range

Find order items priced from 100 to 500:

-- Items priced from 100 to 500
SELECT order_id, product_id, price
FROM olist_order_items_dataset
WHERE price BETWEEN 100 AND 500
LIMIT 10;

Ten of the 37,269 such items.

Exercise 2: Date Range

Find orders placed in March 2018:

-- Orders bought in March 2018
SELECT order_id, order_purchase_timestamp, order_status
FROM olist_orders_dataset
WHERE DATE(order_purchase_timestamp) BETWEEN '2018-03-01' AND '2018-03-31'
LIMIT 10;

Ten of the 7,211 orders of March 2018.

Exercise 3: Payment Installments

Find payments made in 4 to 8 installments:

-- Payments in 4 to 8 installments
SELECT order_id, payment_type, payment_installments, payment_value
FROM olist_order_payments_dataset
WHERE payment_installments BETWEEN 4 AND 8
LIMIT 10;

Ten of the 22,151 such payments.

Exercise 4: NOT BETWEEN

Find reviews scored 1 or 5, using NOT BETWEEN:

-- Reviews scored 1 or 5
SELECT order_id, review_score, review_comment_title
FROM olist_order_reviews_dataset
WHERE review_score NOT BETWEEN 2 AND 4
LIMIT 10;

Ten of the 69,278 such reviews.

Exercise 5: Combined Conditions

Find credit card payments from 200 to 500:

-- Credit card payments from 200 to 500
SELECT order_id, payment_type, payment_value
FROM olist_order_payments_dataset
WHERE payment_type = 'credit_card'
  AND payment_value BETWEEN 200 AND 500
LIMIT 10;

Ten of the 12,759 such payments.

Summary

Key Takeaways

  • BETWEEN keeps the values inside a range
  • Inclusive: both ends are kept
  • It is the same as column >= value1 AND column <= value2
  • It works with numbers, dates and text; text compares by character code
  • The first value must be the smaller one
  • Ranges that meet share their end; use >= and < for them
  • A bare end date stops at that day's first moment
  • Use NOT BETWEEN to leave a range out

Quick Reference

-- A range of numbers, both ends in
WHERE price BETWEEN 50 AND 100

-- A range of dates, by the date
WHERE DATE(order_purchase_timestamp) BETWEEN '2018-01-01' AND '2018-12-31'

-- A range of times, the end left out
WHERE order_purchase_timestamp >= '2018-01-01'
  AND order_purchase_timestamp < '2019-01-01'

-- A range left out
WHERE price NOT BETWEEN 50 AND 100

-- the same as
WHERE price < 50 OR price > 100

When to Use BETWEEN vs Comparison Operators

ScenarioUse
Both ends keptBETWEEN
One end left out>= and <
Ranges that meet>= and <
A range of times ending on a date>= and < the next day

What's Next?

IN Operator keeps the rows whose value is in a list.