In SQL, exists is used to specify a subquery to detect the existence of a row. If so, true or false is returned. Of course, there is also notexists, which works in the opposite way as exists, see the following examples for more information.
In SQL, exists is used to specify a subquery to detect the existence of a row. If yes, true or false is returned. Of course, not exists is returned, which is opposite to exists, see the following examples for more information.
Syntax
EXISTS subquery
Parameters
Subquery
Is a restricted SELECT statement (the COMPUTE clause and the INTO keyword are not allowed)
Result type
Boolean
Result Value
If the subquery contains rows, TRUE. EXISTS (select null) is returned and True is returned.
NOT EXISTS
Not exists is opposite to EXISTS. If the subquery does NOT return rows, the WHERE clause in not exists is satisfied. In this example, find the name of the publisher who does not publish commercial books.
| The Code is as follows: |
|
SELECT pub_name
FROM publishers
WHERE NOT EXISTS
(SELECT *
FROM titles
WHERE pub_id = publishers. pub_id
AND type = 'business ')
Order by pub_name |
In this example, NULL is specified in the subquery and the result set is returned. By using EXISTS, the value is still TRUE.
| The Code is as follows: |
|
SELECT CategoryName
FROM Categories
Where exists (select null)
Order by CategoryName ASC |
Instance
| The Code is as follows: |
|
|
SELECT c. CustomerId, CompanyName
FROM MERs c
Where exists (
SELECT OrderID FROM Orders o
WHERE o. CustomerID = cu. CustomerID)
|