Other Approaches to NOT EXISTSBy Bill Graziano on 23 August 2000 | Tags: SELECT Alex writes "Hello, I have 2 tables with same format, tableA and tableB. I would like to select all those rows that are only in tableA but not tableB. Is there any way to do this other than using "where not exists ... "? I think the NOT EXISTS clause make my query very slow..."
First off all you must accept that the only way for SQL Server to find out what is in TableA but not TableB is to go all the way through both tables. If you use only indexed fields it will be MUCH faster.
For this query, assume TableA has a unique key TableA_ID and TableB has a unique key TableB_ID. These fields are used to match the records. These fields will match if the records match. SELECT A.TableA_ID, B.TableB_ID A left join will return all the rows in TableA and only those rows in TableB that match TableA. The field B.TableB_ID will be NULL for each record where there is no matching entry in TableB.If you really need to compare every single field your ON clause will get very large (because you will join on every field) and this query will get very slow.
|
- Advertisement - |