MySQL EXISTS Operator with Examples

How to Use The MySQL EXISTS Operator

In this tutorial, you will learn how to use the MySQL EXISTS operator. MySQL EXIST operator is often used in subqueries to test whether any record in a subquery exists.

If the subquery returns one or more records, the EXISTS operator returns true; otherwise, it returns false.

Learn more:

MySQL EXISTS Syntax

The syntax of the EXISTS operator is as follows:

SELECT column_name(s)

FROM table_name

WHERE EXISTS

   (SELECT *

   FROM table_name

   WHERE where_conditions);

Examples

As shown in the tables below, assume that the database contains tables named "customers" and "orders," which contain data for the demo.

Customers:

customer_idcustomer_codecustomer_namecountry
1#CID_20010Josh WarnerJapan
2#CID_20011Lisa RamseySouth Korea
3#CID_20012Clifton ChristensenJapan
4#CID_20013Iris WilkersonUnited State
5#CID_20014Charles HarmonJapan
6#CID_20015Glen WoodUnited State
7#CID_20016Francis LewisGermany
8#CID_20017William BarnettChina

Orders:

order_idcustomer_idorder_numberorder_dateamount
11#ORD_000102019-05-131980.00
22#ORD_000112019-05-151350.50
31#ORD_000122019-05-071230.40
41#ORD_000132019-05-231200.00
52#ORD_000142019-05-313450.00
63#ORD_000152019-06-023470.50
74#ORD_000162019-06-031230.80
85#ORD_000172019-06-061998.00

Example 1:

Let's take a look at the following SQL query:

SELECT * FROM customers c

WHERE EXISTS

    (SELECT * FROM orders o);

There is no condition specified in the subquery, so the EXISTS operator returns true because there are records in the orders table.
MySQL will return all records in the "customers" table.

Example 2:

In this example, suppose you need to retrieve all customers who have placed at least one order.
The SQL query would look like this:

SELECT * FROM customers c

WHERE EXISTS

    (SELECT * FROM orders o

    WHERE c.customer_id = o.customer_id);

MySQL returns five records because five customers placed orders in the "orders" table.

Example 3:

Here is an example of setting multiple conditions for a subquery:

SELECT * FROM customers c

WHERE c.country = "Japan" AND EXISTS

    (SELECT * FROM orders o

    WHERE c.customer_id = o.customer_id AND o.order_date BETWEEN

"2019-05-05" AND "2019-05-16");

MySQL returns all customers in Japan that placed orders between 05/05/2019 and 05/16/2019. There is only one record that meets the specified conditions.

Summary

In this MySQL tutorial, you learned how to use the MySQL EXISTS operator. It is often used in subqueries and returns true if the subquery returns any records and false otherwise.


See also:
MySQL LIKE Operator Pattern Matching and Examples
MySQL SUBSTRING_INDEX Function with Examples
MySQL ROW_NUMBER Function with Examples
MySQL CONCAT() Function | Concatenate Strings in MySQL
MySQL IN Operator with Examples

Leave a Comment