Question

We have 500k records in a SQL table. Below is table structure

UserID varchar
FirstName varchar
LastName varchar
Address varchar

We need to delete 50K records in this table. We tried below approach

Approach 1: This has 50K DELETE statements which takes around 40 minutes

DELETE FROM [dbo].[Table] WHERE UserID = 'tom345'
DELETE FROM [dbo].[Table] WHERE UserID = 'john45'

and so on until 50K DELETE statements

Approach 2: This contains all 50K user id in IN statement but it takes more that 40 minutes

DELETE FROM [dbo].[Table] WHERE UserID IN ( 'tom345', 'john45',  .... ) 

Is there any other approach which takes less time comparatively?

Was it helpful?

Solution

Create a temp table, put in your users and use that in your delete statement:

CREATE TABLE delete_users (user_id ... primary key);
INSERT INTO delete_users (user_id) values (...),(...)...;
DELETE FROM  [dbo].[Table] x 
WHERE EXISTS (
    SELECT 1 FROM delete_users y WHERE x.user_id = y.user_id
);
DROP TABLE delete_users;
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top