In and Between Operators Cheat Sheet > Querying with SQL

 IN and BETWEEN Operators

Consider the case of a typical e-commerce scenario. Users generally search for the products that belong to a list of brands, or the products that lie within a particular price range.

In such scenarios, we use the IN operator to check if a value is present in the list of values. And, BETWEEN operator is used to check if a particular value exists in the given range.

Let’s learn about these operators in detail using the following database.

Database The database contains a

product
table that stores the data of products like name, category, price, brand and rating. You can check the schema and data of
product
table in the code playground.

IN Operator

Retrieves the corresponding rows from the table if the value of column(c1) is present in the given values(v1,v2,..).

Syntax

SELECT
*
FROM
table_name
WHERE
c1 IN (v1, v2,..);
SQL

Example

Get the details of all the products from

product
table, where the
brand
is either "Puma", "Mufti", "Levi's", "Lee" or "Denim".

SELECT
*
FROM
product
WHERE
brand IN ( "Puma", "Levi's", "Mufti", "Lee", "Denim");
SQL
Output
namecategorypricebrandrating
Blue ShirtClothing750Denim3.8
Blue JeansClothing800Puma3.6
Black JeansClothing750Denim4.5
...............

Try it Yourself!

  • Get all the products from
    product
    table, that belong to "Britannia", "Lay's", "Cadbury" brands from the "Food" category.

BETWEEN Operator

Retrieves all the rows from table that have cloumn(c1) value present between the given range(v1 and v2).

Syntax

SELECT
*
FROM
table_name
WHERE
c1 BETWEEN v1
AND v2;
SQL
Note

BETWEEN
operator is inclusive, i.e., both the lower and upper limit values of the range are included.

Example

Find the products with

price
ranging from 1000 to 5000.

SELECT
name,
price,
brand
FROM
product
WHERE
price BETWEEN 1000
AND 5000;
SQL
Output
namepricebrand
Blue Shirt1000Puma
Smart Cam2600Realme
Realme Smart Band3000Realme

Possible Mistakes

  1. When using the
    BETWEEN
    operator, the first value should be less than second value. If not, we'll get an incorrect result depending on the DBMS.
SELECT
name,
price,
brand
FROM
product
WHERE
price BETWEEN 500
AND 300;
SQL
Output
namepricebrand
  1. We have to give both lower limit and upper limit while specifying range.
SELECT
name,
price,
brand
FROM
product
WHERE
price BETWEEN
AND 300;
SQL
Error: near "AND": syntax error
SQL
  1. The data type of the column for which we're using the
    BETWEEN
    operator must match with the data types of the lower and upper limits.
SELECT
name,
price,
brand
FROM
product
WHERE
name BETWEEN 300
AND 500;
SQL
Output
namepricebrand

Try it Yourself!

  • Get all the products from
    product
    table with
    rating
    greater than 4.3 and less than 4.8

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form