Click here to Skip to main content
15,892,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am trying to delete the records from primary key table which are not present in foreign key table using sub query. Initially it was working fine but as data become huge it takes lot of time to execute and results in "time out" .The primary key is of type uniqueidentifier , doets this causing problem ?

Consider a table Employe having EmpID uniqueidentifier and Name varchar(200) as columns and consider Project table having ProjectID uniqueIdentifier and EmpID [FK] and ProjectName varchar(200) as columns

Now the query i have written to delete record from Employe table is as below

SQL
Delete from Employe where EmpID not in(select EmpID from Project with(nolock))



Please suggest me how to solve the issue.

Thanks in advance .
Posted
Comments
ZurdoDev 6-Apr-15 14:03pm    
Just increase the timeout. And make sure you have an index on EmpID.
PIEBALDconsult 6-Apr-15 14:07pm    
Don't use IN or NOT IN with a subquery; try a LEFT OUTER JOIN.

1 solution

If SQL Server, then try something like this:

SQL
DELETE FROM Employe
FROM Employe A
LEFT OUTER JOIN Project B
ON A.EmpID = B.EmpID 
WHERE B.EmpID IS NULL


(Not tested.)

Generally, a JOIN will perform much better than a subselect.

https://msdn.microsoft.com/en-us/library/ms189835.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900