SQL Between
SQL Between
a maximum value and a minimum value. It is always used in the WHERE clause.
Syntax
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2';
This will select all rows whose column has a value between 'value1' and 'value2.'
Examples
Table Store_Information
Store_Name Sales Txn_Date
Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
San Francisco 300 Jan-08-1999
Boston 700 Jan-08-1999
Example 1
To select view all sales information between January 6, 1999, and January 10, 1999,
we key in,
SELECT *
FROM Store_Information
WHERE Txn_Date BETWEEN 'Jan-06-1999' AND 'Jan-10-1999';
Note that date may be stored in different formats in different databases. This
tutorial simply choose one of the formats.
Result:
BETWEEN is an inclusive operator, meaning that 'value1' and 'value2' are included
in the result. If we wish to exclude 'value1' and 'value2' but include everything
in between, we need to change the query to the following:
SELECT "column_name"
FROM "table_name"
WHERE ("column_name" > 'value1')
AND ("column_name" < 'value2');
Example 2
We can also use the BETWEEN operator to exclude a range of values by adding NOT in
front of BETWEEN. In the above example, if we want to show all rows where the Sales
column is not between 280 and 1000, we will use the following SQL:
SELECT *
FROM Store_Information
WHERE Sales NOT BETWEEN 280 and 1000;
Result:
Store_Name Sales Txn_Date
Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Exercises
For these exercises, assume we have a table called User_Sales with the following
data:
Table User_Sales
First_Name Last_Name Birth_Date Gender Joi n_Date Total_Sales
Sophie Lee Jan-05-1960 F Apr-05-2015 500
Richard Brown Jan-07-1975 M Apr-05-2015 200
Jamal Santo Oct-08-1983 M Apr-09-2015 350
Casey Healy Sep-20-1969 M Apr-09-2015 80
Jill Wilkes Nov-20-1979 F Apr-15-2015 210
1. Which of the following SQL statement is valid? (There can be more than one
answer)
a) SELECT * FROM User_Sales WHERE Total_Sales BETWEEN 200 OR 300;
b) SELECT * FROM User_Sales WHERE Total_Sales IS BETWEEN 200 OR 300;
c) SELECT * FROM User_Sales WHERE Total_Sales IS BETWEEN 200 AND 300;
d) SELECT * FROM User_Sales WHERE Total_Sales BETWEEN 200 AND 300;