TSO-ISPF JCL COBOL VSAM DB2 CICS Tools Articles Job Portal Forum Quiz Interview Q&A

DB2 - SQL IN Operator


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.

Syntax:

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);

DB2 Database:

Below is a selection from the "Product" table in the DB2 database.

ProductIDProductNameCategoryPriceQtyOnHandTotalValue
7001MouseAccessories75.00
7002Harddrive65.00201,300
7003KeyboardAccessories36.00331,118.00
7004RAMComponents23.5016376.00
7005HondaBikes1,200
7006PEN7.451074.50
7007CddriveAccessories75.00
7008SpeakerAccessories75.00


Example 1: Using the IN Operator:

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');
Result:
ProductIDProductNameCategoryPriceQtyOnHandTotalValue
7001MouseAccessories75.00
7003KeyboardAccessories36.00331,118.00
7004RAMComponents23.5016376.00
7005HondaBikes1,200
7007CddriveAccessories75.00
7008SpeakerAccessories75.00


Example 2: Using the NOT Operator

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".

Example:

SELECT *
  FROM Product
  WHERE Category NOT IN ('Accessories', 'Components', 'Bikes');
Result:
ProductIDProductNameCategoryPriceQtyOnHandTotalValue
7002Harddrive65.00201,300
7006PEN7.451074.50

Example 3: Using IN Operator with SELECT

The following SQL statement selects all students that are from the same countries as the Teachers:

Example:

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!

Are you looking for Job Change? Job Portal