← Python lessons

SQL BETWEEN

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

SQL BETWEEN keeps the rows whose number lies in a range. WHERE pages BETWEEN 240 AND 300 keeps every value from 240 to 300, and both end values are included.

The examples below use this books table. Change a query and press Run to see its result.

Table: books

titleauthorpages
WonderR. J. Palacio320
MatildaRoald Dahl240
HolesLouis Sachar272
The BFGRoald Dahl208
BoyRoald Dahl176

Keep numbers in a range with BETWEEN

Write the column, then BETWEEN, the low number, AND and the high number. This query keeps the books with 240 to 300 pages:

SELECT title, pagesFROM booksWHERE pages BETWEEN 240 AND 300;

Matilda and Holes are in the result. Matilda has exactly 240 pages, the low end, and BETWEEN keeps it. Wonder has more than 300 pages, so it is left out.

Check that both end values are kept

The high end is kept too. Here the range is 208 to 240, and both books that sit on an end are kept:

SELECT title, pagesFROM booksWHERE pages BETWEEN 208 AND 240;

Matilda (240) and The BFG (208) are both kept. Always write the low number first: BETWEEN 240 AND 208 keeps no rows at all.

Use BETWEEN as one condition among others

BETWEEN is one condition, so it can follow another one with AND. The AND inside BETWEEN 200 AND 250 belongs to the range:

SELECT title, pagesFROM booksWHERE author = 'Roald Dahl'  AND pages BETWEEN 200 AND 250;

Matilda and The BFG are in the result. Boy is by Roald Dahl, but 176 is outside the range.

Note: The numbers in BETWEEN have no quotes, just like with >=.

See also: SQL Comparison Operators.

Your turn

Add a WHERE line with BETWEEN so the query shows only the books with 170 to 210 pages.

🎯 Goal — make your query show exactly:
title   | pages
--------+------
The BFG | 208
Boy     | 176
(2 rows)
-- add a WHERE line after FROM, and move the ; to the endSELECT title, pagesFROM books;