Other Approaches to NOT EXISTS

By 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
FROM TableA A
LEFT JOIN TableB B
ON A.TableA_ID = B.TableB_ID
WHERE B.TableB_ID IS NULL


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.


Related Articles

Joining to the Next Sequential Row (2 April 2008)

Writing Outer Joins in T-SQL (11 February 2008)

How to Use GROUP BY with Distinct Aggregates and Derived tables (31 July 2007)

How to Use GROUP BY in SQL Server (30 July 2007)

SQL Server 2005: Using OVER() with Aggregate Functions (21 May 2007)

Server Side Paging using SQL Server 2005 (4 January 2007)

Using XQuery, New Large DataTypes, and More (9 May 2006)

Counting Parents and Children with Count Distinct (10 January 2006)

Other Recent Forum Posts

Troubleshooting Deadlocks in SQL Server (1d)

Last Login date and time (2d)

Negative effects of High VLF counts (2d)

Need to return a value that indicates that a record has been added, but not when a record is modified (3d)

Indexex on low cardinality fields (3d)

Error in stored procedure (4d)

Spam post flagging (4d)

Update Microsoft SQL Server (RTM) 12.0.2000.8 to latest v14 (12.0.6449.1) (4d)

- Advertisement -