Reputation: 323
I have a simple SQL query:
SELECT
columnA, columnB, columnC...
FROM
(SELECT
columnA, columnB, columnC...
FROM
SomeTable) Table1
WHERE NOT EXISTS
(SELECT
columnA
FROM
SomeOtherTable st
WHERE
st.columnB = Table1.columnB)
Can anyone give me a suggestion how to rewrite this query for better performance? I mean to include the WHERE NOT EXISTS
clause in Table1.
Upvotes: 3
Views: 22866
Reputation: 18659
How about this:
SELECT columnA, columnB, columnC...
FROM SomeTable
WHERE (SELECT COUNT(*) FROM SomeOtherTable st WHERE st.columnB = SomeTable.columnB)=0;
Upvotes: 1
Reputation: 174397
You can use this:
select Table1.*
from (select * from SomeTable) Table1
left outer join SomeOtherTable sot
on Table1.columnB = sot.columnB
where sot.columnB is null;
For the performance it is important to have indexes on columnB
on both tables.
Upvotes: 7