EXISTS CLAUSE
suggest changeCustomer table:
| Id | FirstName | LastName |
|---|---|---|
| 1 | Ozgur | Ozturk |
| 2 | Youssef | Medi |
| 3 | Henry | Tai |
Order Table
Id | CustomerId | Amount|
—— | —— | —— |
1 | 2 |123.50|
2 | 3 |14.80|
Get all customers with at least one order
ORDER is a reserved word. Quote it, or use a table name that is not reserved.
SELECT * FROM Customer WHERE EXISTS (
SELECT * FROM "Order" WHERE "Order".CustomerId = Customer.Id
)
Result:
| Id | FirstName | LastName |
|---|---|---|
| 2 | Youssef | Medi |
| 3 | Henry | Tai |
Get all customers with no order
SELECT * FROM Customer WHERE NOT EXISTS (
SELECT * FROM "Order" WHERE "Order".CustomerId = Customer.Id
)
Result
Id | FirstName |LastName|
—— | —— | —— |
1 | Ozgur |Ozturk
Purpose
EXISTS, IN, and JOIN can sometimes produce the same result, but they are not equivalent:
EXISTSchecks whether a matching row exists in another tableINcompares a value with a list or with a subqueryJOINretrieves columns from other tables
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents