
For an instructor lead, in-depth look at learning SQL click below.
Structured Query Language, or SQL, is a standard programming language for interacting with relational databases. One of the most common tasks you will do with SQL is retrieving records from a database. Sometimes, you may need to retrieve based on a list of specific values; this is where SQL’s IN clause comes into play.
Using the IN Clause
The IN clause in SQL is used to match the value in a column with multiple possible values. It behaves similarly to multiple OR conditions and is used when we want to match a column value with more than one value.
The Syntax
|
1 2 3 4 5 |
SELECT column_name FROM table_name WHERE column_name IN (value1, value2, value3, ...); |
Example:
Let’s say we have a table named ‘Customers’, which includes columns like ‘CustomerId’, ‘Name’, ‘State’ etc.
|
1 2 3 4 5 |
SELECT * FROM Customers WHERE State IN ('California','New York','Texas'); |
This SQL code will return all records from the ‘Customers’ table where ‘State’ is either ‘California’, ‘New York’, or ‘Texas’.
Using the IN Clause with Subqueries
Another method to retrieve records based on a list of values is by using subqueries. Subqueries can return multiple records, making them perfect for using with the IN clause.
The Syntax
|
1 2 3 4 5 |
SELECT column_name FROM table_name WHERE column_name IN (subquery); |
Example:
Suppose we have another table named ‘Orders’ with ‘CustomerId’, ‘OrderId’, ‘Amount’. We want to find customers who have placed an order greater than $200.
|
1 2 3 4 5 6 7 8 |
SELECT * FROM Customers WHERE CustomerId IN (SELECT CustomerId FROM Orders WHERE Amount > 200); |
In this case, the subquery will return a list of ‘CustomerId’s which have orders of amount greater than $200. The main query then checks the ‘Customers’ table to retrieve the records of those customers.
To conclude, the IN clause in SQL is a very handy tool that allows you to filter records against a list of known values or subqueries, making it indispensable in your toolbox of SQL techniques.
