We can use MySQL EXIST operator to test for the existence of a record in the subquery. In other words, we can say that EXIST operator checks if a subquery returns any rows. The syntax of using EXIST operator with MySQL subquery is as follows −
Syntax
WHERE EXISTS (Subquery)
The above EXIST (subquery) expression returns TRUE if the subquery returns at least one row, otherwise it returns false.
Example
To make it understand we are using the data from the following tables −
mysql> Select * from Customers; +-------------+----------+ | Customer_Id | Name | +-------------+----------+ | 1 | Rahul | | 2 | Yashpal | | 3 | Gaurav | | 4 | Virender | +-------------+----------+ 4 rows in set (0.00 sec) mysql> Select * from Reservations; +------+-------------+------------+ | ID | Customer_id | Day | +------+-------------+------------+ | 1 | 1 | 2017-12-30 | | 2 | 2 | 2017-12-28 | | 3 | 2 | 2017-12-29 | | 4 | 1 | 2017-12-25 | | 5 | 3 | 2017-12-26 | +------+-------------+------------+ 5 rows in set (0.00 sec)
Following is MySQL subquery with EXIST using the above-mentioned tables −
mysql> Select Name from customers WHERE EXISTS (SELECT * FROM Reservations WHERE Customers.customer_id = Reservations.customer_id); +---------+ | Name | +---------+ | Rahul | | Yashpal | | Gaurav | +---------+ 3 rows in set (0.06 sec)
The above query gives the names of the customers who have made a reservation.