smartyfy.mrindigi.com

Databases & SQL Master Course — 012. Ranges with BETWEEN

Lesson 012 Ranges with BETWEEN

A price band and a monthly delivery report are both range questions, but they need different endpoint rules. A customer may want a book priced exactly at the budget ceiling; a monthly report must stop before the following month begins. This lesson makes those boundaries explicit and testable.

Prerequisites and objectives

Complete lesson 11 first. You should already be comfortable with SELECT, WHERE, ORDER BY, NULL, aliases, and the four-book practice catalog. No Python knowledge is needed. Use inclusive BETWEEN, distinguish it from a half-open interval, and test numeric and consistently formatted date-like text at both endpoints.

Build a fresh practice database

Run this setup once in a new, empty SQLite scratch database and keep the connection open. Start another empty database to reset. Never use important data. These records are fictional; prices are integer cents and stock counts copies.

The added deliveries table contains the first and last whole-second March timestamps, the first April timestamp, and an unknown. All timestamps share one timezone and format.

PRAGMA foreign_keys = ON;
CREATE TABLE authors (
  author_id INTEGER PRIMARY KEY,
  author_name TEXT NOT NULL
);
CREATE TABLE books (
  book_id INTEGER PRIMARY KEY,
  title TEXT NOT NULL,
  author_id INTEGER NOT NULL REFERENCES authors(author_id),
  genre TEXT NOT NULL,
  price_cents INTEGER NOT NULL,
  stock INTEGER NOT NULL
);
INSERT INTO authors (author_id, author_name) VALUES
  (1, 'Mira Chen'), (2, 'Omar Silva'), (3, 'Nia Patel');
INSERT INTO books
  (book_id, title, author_id, genre, price_cents, stock) VALUES
  (101, 'River Maps', 1, 'Travel', 1800, 4),
  (102, 'SQL Trail', 2, 'Technology', 2500, 8),
  (103, 'Garden Notes', 3, 'Nature', 1200, 0),
  (104, 'Night Signals', 1, 'Fiction', 1800, 5);

CREATE TABLE deliveries (
  delivery_id INTEGER PRIMARY KEY,
  received_at TEXT
);
INSERT INTO deliveries (delivery_id, received_at) VALUES
  (1, '2026-03-01 00:00:00'),
  (2, '2026-03-31 23:59:59'),
  (3, '2026-04-01 00:00:00'),
  (4, NULL);

1. Give both endpoints a meaning

BETWEEN expresses an inclusive interval. A price between 1200 and 1800 includes both amounts. Before writing SQL, record the unit, lower limit, upper limit, and whether each boundary belongs in the answer. “Midpriced” is too vague to implement; “at least 1200 cents and at most 1800 cents” is testable.

For ordinary numeric values, price_cents BETWEEN 1200 AND 1800 has the same truth conditions as price_cents >= 1200 AND price_cents <= 1800. The AND inside BETWEEN separates its two bounds; it does not begin an unrelated rule. Add another AND after the complete range when you also need a stock requirement.

2. Check reversed and missing bounds

SELECT 1800 BETWEEN 1200 AND 1800 AS on_upper,
       1800 BETWEEN 1800 AND 1200 AS reversed,
       1500 BETWEEN 1200 AND NULL AS unknown;

Expected output:

on_upper | reversed | unknown
1 | 0 | NULL

The first probe confirms the upper endpoint is included. The second does not silently reorder the limits: an ordinary number cannot be simultaneously at least 1800 and at most 1200. The third cannot establish whether 1500 meets an unknown upper limit. Validate the intended lower and upper values before interpreting an empty result as evidence that no records qualify.

A missing bound does not always make a range unknown: a value below a known lower bound already fails. Avoid unspecified bounds unless their meaning is deliberate.

3. Understand what date-like text compares

SQLite can store date and time information as text. These examples deliberately use fixed-width, year-first strings, so their ordinary text order matches chronological order within the shared timezone. The column name alone supplies no date validation. Mixed formats, timezone offsets, unpadded components, or invalid calendar dates require cleaning or a suitable date-time strategy before this shortcut is trustworthy.

For a whole month, prefer a half-open interval: include the starting instant and exclude the next month’s starting instant. This avoids guessing the last representable fraction of a second. A bare end-date string also creates a trap: a timestamp later on that date compares after the shorter string, so an inclusive BETWEEN ending at that string can omit the very day the writer intended to include.

A numeric line includes both1200 and1800 cents for BETWEEN, admitting books103,101,104 and excluding book102 at2500. A second interval includes March1 at00:00:00 with a filled endpoint and excludes April1 at00:00:00 with an open endpoint.
BETWEEN includes both numeric endpoints. A complete-month timestamp filter is usually clearer as start-inclusive and next-start-exclusive, avoiding assumptions about the last possible fractional second. Open full-size diagram

Four worked exercises

Exercise 1: Include both prices

Find catalog books priced from 1200 through 1800 cents. Predict how many books sit exactly on either boundary.

Worked answer and explanation
SELECT book_id, price_cents FROM books
WHERE price_cents BETWEEN 1200 AND 1800
ORDER BY book_id;

Expected output:

book_id | price_cents
101 | 1800
103 | 1200
104 | 1800

The lower boundary contributes Garden Notes. River Maps and Night Signals both meet the upper boundary. SQL Trail is above the band. This result demonstrates that a range can admit several rows with the same endpoint value; BETWEEN neither removes repeated prices nor selects only one boundary record.

Exercise 2: Combine range and availability

Use the same inclusive price band, but show only books that customers could buy from the recorded stock.

Worked answer and explanation
SELECT book_id, title FROM books
WHERE price_cents BETWEEN 1200 AND 1800
  AND stock > 0
ORDER BY book_id;

Expected output:

book_id | title
101 | River Maps
104 | Night Signals

Finish the range expression before adding the stock predicate. The price test admits three rows, but the extra requirement rejects the zero-stock row. This is a useful distinction between the width of a numeric interval and the additional operational rules used to choose records within that interval.

Exercise 3: Select a complete month

Return every known March delivery, including the first instant of March and the final stored March timestamp, while excluding April.

Worked answer and explanation
SELECT delivery_id, received_at FROM deliveries
WHERE received_at >= '2026-03-01 00:00:00'
  AND received_at < '2026-04-01 00:00:00'
ORDER BY delivery_id;

Expected output:

delivery_id | received_at
1 | 2026-03-01 00:00:00
2 | 2026-03-31 23:59:59

The start uses greater-than-or-equal; the end uses strictly less-than. Delivery 3 is exactly the next month’s starting boundary and is excluded. Delivery 4 has no known time and cannot be assigned to March. The same interval convention still works if later data includes fractional seconds in a consistent sortable representation.

Exercise 4: Investigate outside and unknown

Build an exception list containing timestamps outside March plus records with no timestamp. Missing time is explicitly a review reason.

Worked answer and explanation
SELECT delivery_id, received_at FROM deliveries
WHERE received_at < '2026-03-01 00:00:00'
   OR received_at >= '2026-04-01 00:00:00'
   OR received_at IS NULL
ORDER BY delivery_id;

Expected output:

delivery_id | received_at
3 | 2026-04-01 00:00:00
4 | NULL

The first two alternatives are the complement of the known half-open interval. The third adds unknown records because the request requires review, rather than pretending they have a date outside March. Writing these categories explicitly gives a future reviewer a clear explanation for every returned row.

Pitfalls and boundary design

NOT BETWEEN means outside an inclusive interval for known comparable values. It is useful for known prices below the lower limit or above the upper limit, but it does not automatically include a missing price. Decide whether unknown values belong in an exception report and add a separate IS NULL branch if they do.

Test just below, exactly on, and just above each boundary, plus a middle value and NULL where allowed. With integer cents, “just above” means one cent; timestamp precision belongs to the data contract.

Keep units consistent: cents need a cents-denominated ceiling. Do not mix local and universal timestamps just because the strings look orderly.

Knowledge check

Question 1

Which known values are inside BETWEEN 10 AND 20?

  1. Only values strictly between them
  2. Ten through twenty, including both
  3. Ten through nineteen only
  4. Eleven through twenty only
Answer and explanation

B. Both endpoints are included. Use explicit comparison operators if one endpoint must be excluded.

Question 2

What does 15 BETWEEN 20 AND 10 return?

  1. True because SQLite sorts the bounds
  2. NULL because the bounds differ
  3. False
  4. A syntax error
Answer and explanation

C. BETWEEN preserves the written lower and upper positions. Fifteen does not meet either required boundary direction.

Question 3

Which interval is appropriate for all March timestamps?

  1. Greater than March 1 and less than March 31
  2. BETWEEN March 1 and March 31 with bare dates
  3. At least March 1 midnight and before April 1 midnight
  4. At least March 1 midnight and at most April 1 midnight
Answer and explanation

C. A half-open interval includes the first instant and excludes the next month. The other choices can omit March records or include April.

Question 4

Why do these timestamp strings sort chronologically?

  1. TEXT columns always understand dates
  2. Their consistent year-first fixed-width format and timezone preserve order
  3. The word received appears in the column name
  4. BETWEEN converts every string into a date
Answer and explanation

B. The representation creates the ordering property. Arbitrary text and mixed date formats do not receive automatic calendar interpretation.

Question 5

A report must include unknown prices as exceptions. What should its range filter add?

  1. An explicit OR price_cents IS NULL
  2. A larger upper bound
  3. ORDER BY price_cents
  4. A quoted NULL string
Answer and explanation

A. Missingness is a separate policy branch. Changing the size or ordering of a known-value interval does not include unknown comparisons.

Summary

Define endpoint inclusion, units, and representation before choosing a range operator. BETWEEN is a concise inclusive test; explicit comparisons express half-open periods cleanly. Prove the result with records exactly on both boundaries, and treat missing values according to a stated reporting policy.

SQLite behavior and primary references

Verified with SQLite 3.53.1. Run the SQL in a SQLite tool; the verification script is for course maintenance. Other database engines can differ in Boolean displays, comparison rules, and text matching. This lesson uses ordinary SQLite features, with any important portability limits explained above.