In MySQL, The EXISTS keyword is used in a subquery to test whether the result of the subquery is not empty.
The EXISTS condition is typically used with the WHERE clause to check for the existence of rows that satisfy certain conditions.
The "EXISTS" condition is particularly useful when we want to filter rows based on the existence or non-existence of related records in another table.
Keep in mind that the subquery inside the EXISTS clause should return one or more rows for the condition to be true.
SELECT column1, column2 FROM tableName WHERE EXISTS (subquery);
column1, column2: The columns we want to retrieve from the table.
table_name: The name of the table from which we want to retrieve data.
EXISTS: A condition that returns true if the specified subquery returns one or more rows.
The below query will retrieve all the users from the `users` table who have placed orders in the `orders` table. You can use the `EXISTS` condition to check which users have placed orders.
SELECT * FROM users u WHERE EXISTS ( SELECT 1 FROM orders o WHERE u.userId = o.userId );
In the above example, the outer query selects all columns from the "users" table.
"EXISTS" condition checks whether there is any row in the `orders` table where the "userId" from `users` table matches the "userId" in the inner query `orders` table.
This will retrieve all the users from the `users` table who have placed orders in the `orders` table. You can use the `NOT EXISTS` condition to check which users have not placed an order in the `orders` table.
SELECT * FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id );
We can also use "NOT EXISTS" to check for the absence of rows that satisfy certain conditions.
The above query will retrieve all users who have not placed an order in the orders table.