Friday, June 24, 2016

DELETE WHERE NOT EXISTS

I was putting together a procedure earlier for a fairly common ETL need -- remove records from one table that no longer exist in another table.  A simple WHERE NOT EXISTS, right?   Well, I caught myself in a syntax error, so I thought I would post it here for all of you.

In this example, we want to delete from CustomerSales where CustomerID no longer exists in the Customers table:

             DELETE dbo.CustomerSales a
             WHERE NOT EXISTS(
                    SELECT 1 FROM dbo.Customers b
                    WHERE a.CustomerID = b.CustomerID)
                    
Pretty close, but no cigar.  Try that, and you'll receive this error:

                   Msg 102, Level 15, State 1, Line 3
                       Incorrect syntax near 'a'.

This is the correct syntax:

             DELETE a
             FROM dbo.CustomerSales a
             WHERE NOT EXISTS(
                    SELECT * FROM dbo.Customers b
                    WHERE a.CustomerID = b.CustomerID)

Hopefully useful for somebody!


No comments:

Post a Comment