The IN operator allows you to specify multiple values in a WHERE clause.
IN operator accomplishes the same goal as OR. But IN has the following advantages.
For long lists of valid options, the IN operator syntax is far cleaner and easier to read.
The order of evaluation is easier to manage.
The biggest advantage of IN is that the IN operator can contain another SELECT statement.
SELECT column_name(s) FROM table_name WHERE column_name [NOT] IN (value1, value2, ...); |
or:
SELECT column_name(s) FROM table_name WHERE column_name [NOT] IN (SELECT STATEMENT); |
Below is a selection from the "Product" table in the DB2 database.
ProductID | ProductName | Category | Price | QtyOnHand | TotalValue |
---|---|---|---|---|---|
7001 | Mouse | Accessories | 75.00 | ||
7002 | Harddrive | 65.00 | 20 | 1,300 | |
7003 | Keyboard | Accessories | 36.00 | 33 | 1,118.00 |
7004 | RAM | Components | 23.50 | 16 | 376.00 |
7005 | Honda | Bikes | 1,200 | ||
7006 | PEN | 7.45 | 10 | 74.50 | |
7007 | Cddrive | Accessories | 75.00 | ||
7008 | Speaker | Accessories | 75.00 |
The following SQL statement selects all the products with the Category as "Accessories", "Components" and "Bikes".
SELECT * FROM Product WHERE Category IN ('Accessories', 'Components', 'Bikes'); |
ProductID | ProductName | Category | Price | QtyOnHand | TotalValue |
---|---|---|---|---|---|
7001 | Mouse | Accessories | 75.00 | ||
7003 | Keyboard | Accessories | 36.00 | 33 | 1,118.00 |
7004 | RAM | Components | 23.50 | 16 | 376.00 |
7005 | Honda | Bikes | 1,200 | ||
7007 | Cddrive | Accessories | 75.00 | ||
7008 | Speaker | Accessories | 75.00 |
NOT is a keyword used in a WHERE clause to negate a condition.
The following SQL statement selects all the products that are not the Category as "Accessories", "Components" and "Bikes".
SELECT * FROM Product WHERE Category NOT IN ('Accessories', 'Components', 'Bikes'); |
ProductID | ProductName | Category | Price | QtyOnHand | TotalValue |
---|---|---|---|---|---|
7002 | Harddrive | 65.00 | 20 | 1,300 | |
7006 | PEN | 7.45 | 10 | 74.50 |
The following SQL statement selects all students that are from the same countries as the Teachers:
SELECT * FROM Students WHERE Country IN (SELECT Country FROM Teachers); |
If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!