SQL Server in Operator
SQL Server in Operator
Summary: in this tutorial, you will learn how to use the SQL Server IN operator to
check whether a value matches any value in a list.
SQL Server IN operator overview
The IN operator is a logical operator that allows you to test whether a specified value
matches any value in a list.
The following shows the syntax of the SQL Server IN operator:
column | expression IN ( v1, v2, v3, ...)
In this syntax:
Second, specify a list of values to test. All the values must have the same type as
the type of the column or expression.
If a value in the column or the expression is equal to any value in the list, the result of
the IN operator is TRUE.
The IN operator is equivalent to multiple OR operators, therefore, the following
predicates are equivalent:
column IN (v1, v2, v3)
The following statement finds the products whose list price is one of the following
values: 89.99, 109.99, and 159.99:
SELECT
product_name,
list_price
FROM
production.products
WHERE
list_price IN (89.99, 109.99, 159.99)
ORDER BY
list_price;
The query above is equivalent to the following query that uses the OR operator instead:
SELECT
product_name,
list_price
FROM
production.products
WHERE
list_price = 89.99 OR list_price = 109.99 OR list_price = 159.99
ORDER BY
list_price;
To find the products whose list prices are not one of the prices above, you use the NOT
IN operator as shown in the following query:
SELECT
product_name,
list_price
FROM
production.products
WHERE
list_price NOT IN (89.99, 109.99, 159.99)
ORDER BY
list_price;
SELECT
product_id
FROM
production.stocks
WHERE
store_id = 1 AND quantity >= 30;
You can use the query above as a subquery in as shown in the following query:
SELECT
product_name,
list_price
FROM
production.products
WHERE
product_id IN (
SELECT
product_id
FROM
production.stocks
WHERE
store_id = 1 AND quantity >= 30
)
ORDER BY
product_name;
In this example:
Second, the outer query retrieved the product names and list prices of the
products whose product id matches any value returned by the subquery.
In this tutorial, you have learned how to use the SQL Server IN operator to check
whether a value matches any value in a list or returned by a subquery.