Stop 03 · Filtering DataTopics · 5/8

BETWEEN for Ranges

Part of the SQL Roadmap

In short

Price bands, age groups and date ranges come up constantly. BETWEEN makes them short to write, as long as you remember it includes both ends.

BETWEEN a AND b keeps values in a range and includes both ends. With timestamps this often drops most of the last day, so a half-open range (>= start AND < next_day) is safer.

The jaadu measures a child against a painted height board with two marked lines at the entrance of a colourful fair ride.

Think of it like this

The ride height rule

A mela ride board says "for kids between 100 cm and 140 cm". A child of exactly 140 cm gets on, because both ends count. Now imagine the rule were about dates with clock times: a child arriving at 4 pm on the last day would be turned away, because "the last day" really meant midnight at its start.

Watch it happen

created_at BETWEEN '2026-03-01' AND '2026-03-31'

Mar 01 09:10
0
Mar 15 18:00
1
Mar 31 00:00
2
Mar 31 14:25
3
Apr 01 08:00
4

1/5Five order timestamps around March.

The big ideas

What you need to know

Both ends included

amount BETWEEN 500 AND 1000 means amount >= 500 AND amount <= 1000.

Low value first

BETWEEN 1000 AND 500 returns nothing in PostgreSQL and MySQL. Always write the smaller value first.

Timestamps need half-open ranges

Use >= start AND < day after end. It works for DATE and TIMESTAMP columns alike.

NOT BETWEEN

NOT BETWEEN 500 AND 1000 keeps values below 500 or above 1000.

See it in code

Walk through the code

sql
1-- Price band: both ends included2SELECT product_name, price3FROM products4WHERE price BETWEEN 500 AND 1000;5 6-- All of March 2026 for a TIMESTAMP column7SELECT order_id, created_at8FROM orders9WHERE created_at >= DATE '2026-03-01'10  AND created_at <  DATE '2026-04-01';

1/2Products from ₹500 to ₹1,000, including both prices.

BETWEEN is perfect for numbers and pure DATE columns. For timestamps, the half-open range is safer in every database.

Save yourself the pain

Common mistakes

Oops

created_at BETWEEN '2026-03-01' AND '2026-03-31' on a timestamp column.

Do this instead

Use created_at >= '2026-03-01' AND created_at < '2026-04-01' so the whole last day is included.

Oops

Using BETWEEN for back-to-back bands like 0-500 and 500-1000.

Do this instead

A ₹500 item lands in both. Use >= and < so each value falls in exactly one band.

Your mission

Range checks

~20 min

Quick check

Which filter includes every order placed on 31 March 2026 in a TIMESTAMP column?

Go deeper

  1. 1Find products priced between 500 and 1000 and confirm both ends are included.
  2. 2Filter a timestamp column for one full month using >= first day AND < first day of next month.
  3. 3Check what BETWEEN does when the lower bound is bigger than the upper bound.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge