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.
Is true only if the number of rows that is specified by the subquery is not zero.
Is false only if the number of rows specified by the subquery is zero.
Cannot be unknown.
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:
Orderid | Customernumber | Orderdate |
---|---|---|
1001 | 10 | 2020-09-08 |
1002 | 99 | 2020-09-01 |
1003 | 17 | 2020-08-25 |
1004 | 76 | 2020-09-19 |
1005 | 70 | 2020-09-19 |
Let's look at the "Customers" table data below:
Customernumber | Customername | Country |
---|---|---|
76 | Jack | America |
17 | Jancy | Germany |
20 | Carmen | Pakistan |
10 | Robert | India |
99 | Brian | China |
70 | April | America |
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); |
Customername |
---|
Jack |
Jancy |
Robert |
Brian |
April |
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'); |
Customername |
---|
Brian |
April |
If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!