SQL Server: Safe Bulk DELETE Using JOIN
Delete rows using a JOIN with a preview step to avoid accidental data loss.
- Updated
- Requires
- SQL Server 2008+
- Markdown
Your values
Type your own names and every code block on this page updates, including what Copy copies.
Problem
You need to delete a specific set of rows based on a list or staging table, but want to verify exactly what will be removed before running the delete.
Solution
Preview the affected rows using a SELECT, then run the DELETE using the same JOIN.
-- Preview first
SELECT t.*
FROM target_table t
JOIN #rows_to_delete d ON d.id = t.id;
-- Apply delete
BEGIN TRAN;
DELETE t
FROM target_table t
JOIN #rows_to_delete d ON d.id = t.id;
SELECT @@ROWCOUNT AS rows_deleted;
-- COMMIT;
-- ROLLBACK;
Generate the whole delete (preview, backup, delete, restore) in the Data Fix Script Builder Opens the tool with this example filled in
Notes
- Always run the SELECT preview first.
- Wrapping in a transaction allows quick rollback if the row count is unexpected.
- Useful for removing duplicate or incorrectly imported data.
- Consider backing up affected rows first:
SELECT *
INTO backup_table_20260216
FROM target_table t
JOIN #rows_to_delete d ON d.id = t.id;
Was this useful?
Thanks. What was the problem?