SQL: Structured Query LanguageSQL FundamentalsRange Filtering

How do you filter values within a range using BETWEEN?

Question 22 of 30 · Updated

On this page

Use WHERE column BETWEEN lower_bound AND upper_bound to select values in an inclusive range. Both endpoints are included. For ordinary comparable values, x BETWEEN a AND b has the same truth value as x >= a AND x <= b. SQL retains a row only when the complete WHERE condition evaluates to TRUE.

1. Syntax and meaning#

SQL
SELECT column_name FROM table_name WHERE column_name BETWEEN lower_bound AND upper_bound;

The lower and upper bounds may be literals, parameters or compatible expressions. In an ordinary ascending range, provide the smaller value first. The keyword AND inside BETWEEN separates its two bounds; it is part of the range predicate syntax.

Business rulePredicate
From 100 through 200, inclusiveprice BETWEEN 100 AND 200
Strictly inside the rangeprice > 100 AND price < 200
Include lower but exclude upperprice >= 100 AND price < 200
Outside the inclusive rangeprice NOT BETWEEN 100 AND 200

Choose a predicate based on what the endpoints mean. Do not use BETWEEN when the upper boundary must be excluded.

2. Worked example: product prices#

A shop wants to display products priced from 100 to 200 inclusive. The following CTE constructs a disposable, reproducible dataset using VALUES. No permanent table is required. Integer prices here are illustrative amounts; a production money column may use an exact numeric type or integer minor units.

idprice
199
2100
3150
4200
5201
6NULL
SQL
WITH products(id,price) AS ( VALUES (1,99),(2,100),(3,150), (4,200),(5,201),(6,NULL::integer) ) SELECT id,price FROM products WHERE price BETWEEN 100 AND 200 ORDER BY id;

Result:

idprice
2100
3150
4200

The boundary values 100 and 200 qualify, along with 150. Values 99 and 201 fall outside. The missing price does not qualify because its comparison to known bounds produces UNKNOWN. This query does not modify the source rows.

Loading diagram…

The diagram shows which values satisfy this particular inclusive range. It is a conceptual classification, not a prescription for physical query execution.

3. BETWEEN versus comparison operators#

Here is a side-by-side test of BETWEEN, its expanded form, and NOT BETWEEN. Inspect the predicate values themselves instead of filtering first, so that the FALSE and UNKNOWN cases are visible.

SQL
WITH products(id,price) AS ( VALUES (1,99),(2,100),(3,150), (4,200),(5,201),(6,NULL::integer) ) SELECT id,price, price BETWEEN 100 AND 200 AS inside, price >= 100 AND price <= 200 AS expanded, price NOT BETWEEN 100 AND 200 AS outside FROM products ORDER BY id;
idpriceinsideexpandedoutside
199FALSEFALSETRUE
2100TRUETRUEFALSE
3150TRUETRUEFALSE
4200TRUETRUEFALSE
5201FALSEFALSETRUE
6NULLNULLNULLNULL

The two inside columns match for every tested row. SQL NULL represents the unknown Boolean result in this table. For ordinary column and bound values, NOT BETWEEN corresponds to NOT (price BETWEEN 100 AND 200), or price < 100 OR price > 200. It is not a guarantee that every row excluded by the first WHERE query will appear in the negated query: a NULL price is excluded by both.

With side-effecting or volatile expressions, avoid assuming different textual rewrites have identical expression evaluation counts. For normal data values and simple parameterized bounds, the expanded comparison is the useful semantic model.

4. Reversed and identical bounds#

Ordinary BETWEEN does not automatically reorder the endpoints. If the application passes 200 as the lower bound and 100 as the upper bound, no ordinary non-NULL ordered numeric value can satisfy both comparisons. PostgreSQL supports BETWEEN SYMMETRIC when the requirement is specifically to allow either bound order.

SQL
SELECT 150 BETWEEN 200 AND 100 AS ordinary, 150 BETWEEN SYMMETRIC 200 AND 100 AS symmetric, 100 BETWEEN 100 AND 100 AS same_bound;
ordinarysymmetricsame_bound
FALSETRUETRUE

Equal bounds are valid and act like equality for comparable values. BETWEEN SYMMETRIC is not universally supported; for an application with distinct minimum and maximum fields, validating the bound order is often preferable to silently correcting a user mistake. If a UI intentionally lets users choose endpoints in any order, normalize the inputs or use the dialect's appropriate symmetric predicate.

5. NULL in a range condition#

SQL range predicates obey three-valued logic. With known bounds and a missing value, BETWEEN evaluates to UNKNOWN, as in the product example. But a missing bound does not always make the entire predicate unknown: one comparison may already be FALSE, and FALSE AND UNKNOWN is FALSE.

SQL
SELECT 50 BETWEEN 100 AND NULL::integer AS known_false, 150 BETWEEN 100 AND NULL::integer AS unknown_result;
known_falseunknown_result
FALSENULL

In a filtering context, neither result is TRUE, so neither qualifies. To include unknown prices by deliberate business policy, write WHERE (price BETWEEN 100 AND 200) OR price IS NULL. Do not replace missing prices with zero unless zero is actually the intended business meaning. Optional filter bounds also deserve explicit handling; an omitted minimum is not the same thing as a minimum of NULL. A query builder can omit the corresponding comparison when a bound is absent. These optional-filter expressions are illustrative; the seven executable examples in this lesson are the ones validated.

6. Filtering calendar dates#

For a DATE column, a closed range is often exactly what a user wants. A report from January 1 through January 31 should include both calendar dates.

SQL
WITH events(id,day) AS ( VALUES (1,DATE '2026-01-01'), (2,DATE '2026-01-31'), (3,DATE '2026-02-01') ) SELECT id,day FROM events WHERE day BETWEEN DATE '2026-01-01' AND DATE '2026-01-31' ORDER BY id;
idday
12026-01-01
22026-01-31

Typed date literals avoid ambiguity caused by locale-dependent strings such as 01/02/2026. Use parameters of the correct data type when dates originate from an application. For an inclusive calendar-date range, the end date is included.

7. Timestamp pitfall: an inclusive end date is not an inclusive end day#

A TIMESTAMP includes time of day. The timestamp literal TIMESTAMP '2026-01-31' means midnight at the beginning of January 31, not the end of that day. A BETWEEN predicate ending at that timestamp misses events later on January 31.

SQL
WITH events(id,ts) AS ( VALUES (1,TIMESTAMP '2026-01-01 00:00'), (2,TIMESTAMP '2026-01-31 00:00'), (3,TIMESTAMP '2026-01-31 18:00'), (4,TIMESTAMP '2026-02-01 00:00') ) SELECT id, ts BETWEEN TIMESTAMP '2026-01-01' AND TIMESTAMP '2026-01-31' AS closed_midnight, ts >= TIMESTAMP '2026-01-01' AND ts < TIMESTAMP '2026-02-01' AS half_open FROM events ORDER BY id;
idclosed_midnighthalf_open
1TRUETRUE
2TRUETRUE
3FALSETRUE
4FALSEFALSE

To retrieve a whole month from a timestamp column, prefer ts >= start_of_month AND ts < start_of_next_month. This is a half-open interval. It avoids guessing the last representable fractional second and prevents adjacent reporting windows from sharing a boundary event. This example uses local timestamps without time zone; for timestamp-with-time-zone data, calculate the two boundary instants in the business timezone, accounting for changes in UTC offset. That conversion is outside the scope of this range-predicate lesson and is covered in the date/time material.

8. Decimal and text ranges#

BETWEEN is not limited to integers. PostgreSQL can compare exact decimal values, dates, timestamps and other comparable types.

SQL
SELECT 19.99::numeric BETWEEN 10.00::numeric AND 20.00::numeric AS inside, 20.01::numeric BETWEEN 10.00::numeric AND 20.00::numeric AS outside;
insideoutside
TRUEFALSE

For financial thresholds, exact decimal or integer minor-unit comparisons avoid many floating-point boundary surprises. If a numeric-looking value is stored as text, its comparison may follow lexical rather than numeric order. Text ranges also depend on the applicable collation; a text BETWEEN predicate is not a general prefix search. Use appropriate data types and explicit business rules instead of assuming all ordered values behave like numbers.

9. Combining ranges with additional filters#

An application might require products in a price interval and available in stock. The following is a general SQL template, assuming a products table with the named columns:

SQL
SELECT id, price FROM products WHERE price BETWEEN 100 AND 200 AND in_stock = TRUE ORDER BY id;

Here the first AND belongs to BETWEEN; the second combines the range predicate with another condition. When OR conditions are mixed with AND, parentheses make the intended grouping clear. For example, (price BETWEEN 100 AND 200 OR featured = TRUE) AND in_stock = TRUE requires stock availability regardless of which of the alternative price or featured conditions matches. This template is illustrative and was not executed against a real table.

10. Application integration and performance#

Supabase JavaScript provides gte(column,value) and lte(column,value) modifiers, which express the two inclusive comparisons. A configured client can query an existing table with an illustrative call:

JAVASCRIPT
const { data, error } = await supabase .from('products') .select('id, price') .gte('price', 100) .lte('price', 200) .order('id'); if (error) throw error;

Both comparison filters must match. The official Supabase documentation for gte and lte was consulted for their respective inclusive semantics. This API snippet was not run: it requires a configured client, appropriate schema and permissions. In backend SQL, bind validated typed parameters instead of concatenating user input into a query. Filter criteria are not a substitute for row-level access controls.

A B-tree index on a suitable ordered column can support range predicates. Whether it is chosen depends on selectivity, table size, statistics, other query conditions and the optimizer. BETWEEN is not inherently faster than the equivalent two comparisons. Keep the column comparison compatible with the indexed type; unnecessary casts or functions applied to the column can obstruct use of an ordinary index. Inspect the actual plan and benchmark with representative data rather than guessing. No index was created and no performance measurement was carried out in this lesson.

11. Common mistakes#

MistakeCorrect approach
Assuming BETWEEN excludes endpointsBoth endpoints are included
Passing reversed numeric boundsValidate minimum and maximum, or deliberately use symmetric semantics
Assuming NOT BETWEEN includes NULLExplicitly decide whether missing values belong in the result
Filtering a timestamp through an end-date midnightUse an exclusive next-period boundary for full-day or full-month windows
Comparing numeric strings as if they were numbersUse an appropriate numeric type
Assuming BETWEEN is always fasterCompare actual execution plans
Confusing WHERE filtering with a CHECK constraintWHERE selects rows; constraints enforce rules on stored data

12. Interview-ready answer#

BETWEEN is a SQL range predicate used in WHERE to match values from a lower bound through an upper bound, inclusive. For example, WHERE price BETWEEN 100 AND 200 matches 100, 150 and 200; it is equivalent in truth value to price >= 100 AND price <= 200 for ordinary values. NOT BETWEEN matches values outside that closed range, but does not automatically include NULL. Ordinary BETWEEN requires the bounds in the intended order. For full-day timestamp filters, prefer an inclusive start and exclusive next-day boundary rather than BETWEEN ending at midnight of the last included date.

Quick checks: Is 200 included in BETWEEN 100 AND 200? Yes. Does 150 BETWEEN 200 AND 100 evaluate TRUE? No for ordinary numeric BETWEEN. Does NULL BETWEEN two known bounds qualify in WHERE? No. Does a range on a timestamp automatically include an entire final day? No; the exact endpoint matters.

13. Validation and authoritative references#

Seven read-only PostgreSQL statements were executed using synthetic VALUES data or literal expressions: inclusive numeric filtering; equivalence and NOT BETWEEN; reversed, symmetric and identical bounds; NULL-bound evaluation; calendar dates; timestamp boundary comparison; and decimal range comparisons. All returned the displayed results. General templates, optional filter examples and JavaScript client code were not executed. No schema or production business data changes were made. The Mermaid diagram was structurally checked and stored inside an exact triple-backtick mermaid block; full parser validation and public rendering were unavailable. Supabase's official gte and lte documentation was consulted through its documentation connector. External PostgreSQL references below are authoritative reference destinations but were not live fetched under the offline research exception.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning