100 Days of SQL

sql

Day 72 – SQL EXISTS Keyword

SQL EXISTS keyword is used to check for the existence of a record or set of records in a subquery. The EXISTS operator returns a Boolean value (TRUE or FALSE) indicating whether or not the subquery returns any rows.

The basic syntax for using the EXISTS keyword is as follows:

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

Here, column_name(s) are the columns that you want to retrieve from the table, table_name is the name of the table that you want to query, and subquery is a SELECT statement that returns a set of records to be evaluated.

For example, to check if any orders have been placed by a customer with a customer ID of 1234, the SQL statement would be:

SELECT *
FROM Orders
WHERE EXISTS (
  SELECT *
  FROM Customers
  WHERE Customers.CustomerID = Orders.CustomerID
  AND Customers.CustomerID = 1234
);

In this example, the subquery retrieves all customers with a customer ID of 1234, and the outer query retrieves all orders where the customer ID matches the results of the subquery. If any orders exist for the specified customer ID, the EXISTS operator returns TRUE.

It’s important to note that the EXISTS operator does not return any actual data from the subquery, only a Boolean value indicating whether or not the subquery returns any rows. Therefore, the EXISTS operator is often used in combination with other operators, such as NOT, to check for the absence of a record or set of records.