I have a query sub query below (Purpose search top 2 orders from order table whose freight_charges=2 and get the customers of those orders)
- Working query with IN clause
SELECT *
FROM Customers C
WHERE C.CUST_ID IN (
SELECT TOP 2 CUST_ID
FROM Orders O
where FREIGHT_CHARGES = 2
)
However I want to convert the IN clause into a more efficient EXISTS clause
- Code not working with exists clause
SELECT *
FROM Customers C
WHERE EXISTS (
SELECT TOP 2 CUST_ID
FROM Orders O
where FREIGHT_CHARGES = 2 AND C.CUST_ID = O.CUST_ID
)
In case of the second query I am not retrieving the top 2 cust_id BUT all the records.
Please let me know any implementation to get the desired result.
Edited: Using INNER JOIN as suggested in the answers . I am able to get the correct result. However since I don't want to retrieve any record from Orders table I thought exists would be a better approach performance wise.
SELECT C.*
FROM Customers C
INNER JOIN (
SELECT TOP 2 CUST_ID
FROM Orders
where FREIGHT_CHARGES = 2
) O ON C.CUST_ID=O.CUST_ID