Skip to content
Back to 50 Concepts
Topic 13 of 50query-executionBeginner

# Topic 13: BETWEEN Operator

Inclusive range queries, boundary semantics, timestamp datetime edge cases, and NOT BETWEEN.

1. Definition

The BETWEEN operator matches values within a specified range, inclusive of both lower and upper endpoints.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

BETWEEN is like asking for everyone whose height is from 5 feet to 6 feet, including people who are exactly 5 feet or exactly 6 feet.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

BETWEEN Operator Visual Simulator

Step 1 of 3
SQL>SELECT * FROM orders WHERE total_cents BETWEEN 1000 AND 5000;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for BETWEEN Operator
SQL Input

Initiating BETWEEN Operator

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Doorway measuring tape: Anyone whose height touches or falls between the 5ft and 6ft marks is let through.

4. Real-World Example

Filtering quarterly financial transactions between $100 and $500.

Transactions
idamountstatus
1100.00 (Matched - lower bound)completed
2350.00 (Matched)completed
3500.00 (Matched - upper bound)completed
4500.01 (Excluded)completed
Relational walkthrough: BETWEEN 100.00 AND 500.00 matches rows 1, 2, and 3.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Numeric Range
SELECT id, product_name, price
FROM products
WHERE price BETWEEN 20.00 AND 100.00;
Equivalent to price >= 20.00 AND price <= 100.00.
Step 2: Safe Timestamp Ranges
-- Safer alternative to BETWEEN for timestamps:
SELECT id, event_time
FROM logs
WHERE event_time >= '2026-01-01' AND event_time < '2026-02-01';
Avoids missing events occurring at 2026-01-31 23:59:59.999.

6. Important Rules & Behaviors

RuleBehavioral Explanation
InclusivityBETWEEN is always inclusive of both lower and upper boundary values.
Ordering RequirementBETWEEN a AND b requires a <= b. If a > b, it evaluates to FALSE and returns 0 rows.
Index SSeekableB-Tree indexes efficiently optimize BETWEEN into an index range scan.
Boundary inclusivityBETWEEN is strictly inclusive: val BETWEEN low AND high is identical to val >= low AND val <= high.
Timestamp boundary hazardUsing BETWEEN on timestamps includes midnight of the end date, causing off-by-one errors; use >= AND < instead.

7. Deep Dive: Why BETWEEN is Dangerous for Timestamps

Writing WHERE created_at BETWEEN "2026-01-01" AND "2026-01-31" resolves to 2026-01-31 00:00:00. Any transaction that took place later on January 31st (e.g. 2:00 PM) is silently omitted!

-- DANGEROUS (misses all events after midnight Jan 31):
WHERE created_at BETWEEN '2026-01-01' AND '2026-01-31';

-- ROBUST (Half-open interval >= and <):
WHERE created_at >= '2026-01-01' AND created_at < '2026-02-01';
Caution: Never use BETWEEN on TIMESTAMP or TIMESTAMPTZ columns. Use half-open intervals >= and < instead.

8. Advantages & Disadvantages

Advantages

  • •Clean, readable syntax for bounded integer and numeric ranges.
  • •Directly mapped to B-Tree index range scans.

Disadvantages & Trade-offs

  • •Prone to timestamp bugs due to endpoint inclusion.

9. Common Interview Questions

Q1.Why is BETWEEN considered an antipattern for timestamp and date range queries in production?

BETWEEN is inclusive on both ends. If an engineer writes WHERE created_at BETWEEN '2026-01-01' AND '2026-01-31', the string '2026-01-31' is cast to '2026-01-31 00:00:00.000000'. Any transaction occurring at 10:00 AM or 11:59 PM on January 31st will be silently omitted! The production standard is always half-open intervals: WHERE created_at >= '2026-01-01' AND created_at < '2026-02-01'.

Q2.How does a B-Tree index physically execute a BETWEEN query?

The engine uses the B-Tree index to perform a single binary search seek to find the first leaf entry >= low boundary (O(log N)). Then, because B-Tree leaf pages are doubly linked in sorted order, the engine simply scans along the leaf nodes sequentially until it encounters an entry > high boundary, avoiding any random disk I/O.

Q3.What happens if you reverse the arguments in BETWEEN (e.g. BETWEEN 10 AND 5)?

In SQL, BETWEEN low AND high is defined as value >= low AND value <= high. If you write BETWEEN 10 AND 5, the condition evaluates to value >= 10 AND value <= 5, which is mathematically impossible for any real number. The query will return zero rows with no syntax error or warning.

Q4.What is NOT BETWEEN and how does it handle NULL values?

NOT BETWEEN low AND high is equivalent to value < low OR value > high. If the value is NULL, the comparison yields UNKNOWN and the row is excluded from the result set. Furthermore, if either low or high is NULL, the entire expression evaluates to UNKNOWN.

Q5.Can BETWEEN be used on text and string columns?

Yes, BETWEEN works on any data type with a defined collation order (e.g. WHERE name BETWEEN 'A' AND 'C'). However, string boundaries can be tricky: 'Car' is included because 'Car' <= 'C', but 'Cat' is > 'C' and is excluded. For text ranges, exact prefix matches or LIKE 'A%' are generally preferred.

10. Interview-Ready Answer

“BETWEEN filters values inside an inclusive boundary. While ideal for integers and decimals, half-open intervals (>= start AND < next_period) must be used for timestamps to avoid truncating sub-day records.”

11. Quick Test

Scenario Question:

Given the clause "WHERE score BETWEEN 80 AND 90", will a student with a score of exactly 90 be included?

Select your answer: