Use BETWEEN to Filter Results

suggest change

The following examples use the Item Sales and Customers sample databases.

Note: The BETWEEN operator is inclusive.

Using the BETWEEN operator with Numbers:

SELECT * From ItemSales
WHERE Quantity BETWEEN 10 AND 17

This query returns every ItemSales row whose quantity is greater than or equal to 10 and less than or equal to 17. BETWEEN is unknown when the quantity is NULL, so those rows are not returned. The results will look like:

Id | SaleDate | ItemId | Quantity | Price

—| –––––––| ––––| ———| —— 1 | 2013-07-01 | 100 | 10 | 34.5

4 | 2013-07-23 | 100 | 15 | 34.5 5 | 2013-07-24 | 145 | 10 | 34.5


Using the BETWEEN operator with Date Values:

SELECT * From ItemSales
WHERE SaleDate BETWEEN '2013-07-11' AND '2013-07-24'

If the first bound is greater than the second, BETWEEN matches nothing. This range is 11 July 2013 through 24 July 2013, inclusive.

Id | SaleDate | ItemId | Quantity | Price

—| –––––––| ––––| ———| —— 3 | 2013-07-11 | 100 | 20 | 34.5 4 | 2013-07-23 | 100 | 15 | 34.5 5 | 2013-07-24 | 145 | 10 | 34.5

When the column is a datetime rather than a date, a bare date literal is midnight at the start of that day. Convert the column to a date, or set the upper bound to the start of the next day. Otherwise the rest of the end date is left out.


Using the BETWEEN operator with Text Values:

SELECT Id, FName, LName FROM Customers
WHERE LName BETWEEN 'D' AND 'L';

Live example: SQL fiddle

This query returns customers whose LName is between the strings D and L, inclusive. William Jones and Richard Davis are included. David Miller, which begins with M, is not. A name such as Lee sorts after L and is excluded too.

Id | FName | LName —| ———| —– 1 | William | Jones 3 | Richard | Davis

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents