# 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.
2. Explain Like I'm 5
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 TraceBETWEEN Operator Visual Simulator
SELECT * FROM orders WHERE total_cents BETWEEN 1000 AND 5000;Active InputStep 1: Input & Parsing Stage
Initiating BETWEEN Operator
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Filtering quarterly financial transactions between $100 and $500.
| id | amount | status |
|---|---|---|
| 1 | 100.00 (Matched - lower bound) | completed |
| 2 | 350.00 (Matched) | completed |
| 3 | 500.00 (Matched - upper bound) | completed |
| 4 | 500.01 (Excluded) | completed |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT id, product_name, price FROM products WHERE price BETWEEN 20.00 AND 100.00;
-- Safer alternative to BETWEEN for timestamps: SELECT id, event_time FROM logs WHERE event_time >= '2026-01-01' AND event_time < '2026-02-01';
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Inclusivity | BETWEEN is always inclusive of both lower and upper boundary values. |
| Ordering Requirement | BETWEEN a AND b requires a <= b. If a > b, it evaluates to FALSE and returns 0 rows. |
| Index SSeekable | B-Tree indexes efficiently optimize BETWEEN into an index range scan. |
| Boundary inclusivity | BETWEEN is strictly inclusive: val BETWEEN low AND high is identical to val >= low AND val <= high. |
| Timestamp boundary hazard | Using 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';
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
Given the clause "WHERE score BETWEEN 80 AND 90", will a student with a score of exactly 90 be included?