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

DB2 - SQL Exists Operator


The EXISTS operator tests for the existence of certain rows in a subquery.

The EXISTS operator returns true if the subquery returns one or more records.

The result of the EXISTS operator.

  1. Is true only if the number of rows that is specified by the subquery is not zero.

  2. Is false only if the number of rows specified by the subquery is zero.

  3. Cannot be unknown.

Syntax:

SELECT column_name(s)
    FROM table_name
    WHERE EXISTS
    (SELECT column_name FROM table_name WHERE condition);

Let's look at the "Orders" table data below:

OrderidCustomernumberOrderdate
1001102020-09-08
1002992020-09-01
1003172020-08-25
1004762020-09-19
1005702020-09-19

Let's look at the "Customers" table data below:

CustomernumberCustomernameCountry
76JackAmerica
17JancyGermany
20CarmenPakistan
10RobertIndia
99BrianChina
70AprilAmerica


Example: 1

The following SQL statement returns TRUE and lists the customers who made a order.

SELECT Customername
  FROM Customers
  WHERE EXISTS (SELECT Orderid
                  FROM Orders
                 WHERE Orders.Orderid = Customers.Orderid);
Result:
Customername
Jack
Jancy
Robert
Brian
April


Example: 2

The following SQL statement returns TRUE and lists the customers who made a order on date '2020-09-19'.

SELECT Customername
  FROM Customers
  WHERE EXISTS (SELECT Orderid
                  FROM Orders
                  WHERE Orders.Orderid = Customers.Orderid
                    AND Orderdate='2020-09-19');
Result:
Customername
Brian
April


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