Delete Using INNER JOIN

The need to join tables in order to determine which records to delete is a common requirement. The syntax can be somewhat tricky because you need to use an alias for the table you want to delete from.

Always test DELETE statements prior to running them in your production system.

First, here is a simple example:

DELETE o
FROM #orders o
JOIN #customers c
    ON c.customer_id = o.customer_id
WHERE c.last_name = 'jones'
AND c.first_name = 'alexandria'

The following query will delete all the order records from the customers who have the name alexandria jones. This will only delete records from the orders table, however I strongly suggest you perform a SELECT statement prior to actually performing the delete using the same query as such:

--DELETE o
SELECT o.*
FROM #orders o
JOIN #customers c
    ON c.customer_id = o.customer_id
WHERE c.last_name = 'jones'
AND c.first_name = 'alexandria'

This will show you the exact records you are about to delete. Once you get the count, I actually suggest you take one additional safety measure to ensure you don’t delete more records by using the TOP clause:

--DELETE o
SELECT COUNT(o.*)
FROM #orders o
JOIN #customers c
    ON c.customer_id = o.customer_id
WHERE c.last_name = 'jones'
AND c.first_name = 'alexandria'

-- if the above query returns 5 records, set 5 below
DELETE TOP (5) o
FROM #orders o
JOIN #customers c
    ON c.customer_id = o.customer_id
WHERE c.last_name = 'jones'
AND c.first_name = 'alexandria'

Once again.. test, test, test before you delete!

Featured Articles

 Site Author