Question

I tried this query but I can't get it to work:

It says that there's a syntax error near EXISTS.

SELECT * 
FROM Customers 
WHERE CustomerID EXIST IN (SELECT *, CustomerID FROM Orders);

Thanks in advance.

Was it helpful?

Solution

the error is right. You even wrote Exists in your question but in the example code you wrote exist with no s on the end. See here for the proper syntax

You need to correlate the outer query with the sub query in the exists. It doesn't matter what columns you select because by rule they are not allowed to be evaluated (i.e. select * is fine)

SELECT * 
FROM Customers C
WHERE EXISTS (SELECT * FROM Orders where Orders.CustomerID = C.CustomerID);

OTHER TIPS

Try something like this:

SELECT * FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders);

This is the correct exists syntax, performance wise, this is A LOT better than an IN statement.

SELECT *
FROM Customers c
WHERE EXISTS
  (SELECT 'X' FROM Orders o WHERE o.CustomerID = c.CustomerID);

Why not use a JOIN?

SELECT
    Customers.*
FROM
    Customers
    INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

If you really do want to use EXSITS, the syntax is as follows:

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

And for good measure using IN:

SELECT
    Customers.*
FROM
    Customers
WHERE
    CustomerID IN (SELECT Orders.CustomerID FROM Orders);

If you are on MySQL I'd encourage you to run all 3 with the EXPLAIN statement, so you can see how they differ.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top