Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DELETE from SELECT statement 1

Status
Not open for further replies.

MarkTac

Programmer
Nov 24, 2011
7
Hi,

I'm writing a code to DELETE all duplicate records. I can easily find all duplicates with SELECT statement. However, I'm confused how to integrate my SELECT into DELETE statement:

SELECT [col1], [col2], [col3] FROM [table1] GROUP BY [col1], [col2], [col3] HAVING (COUNT([col2])>0)

Thank you.
 
Well, I have code to remove duplicates using VBA Recordset. However, I was wondering if it is possible by doing SQL DELETE statement.
 

It is easy if you have a unique key in your table.
Do you have a unique key?

Have fun.

---- Andy
 
What I came up with so far but I have to run it several times for multiple duplicates of the same record:

DELETE *
FROM [table1]
WHERE ID IN ( SELECT Min(ID) FROM [table1] GROUP BY [col1], [col2], [col3] HAVING COUNT([col2])>1);
 
How about backing up your database and trying:
Code:
DELETE *
FROM [table1]
WHERE ID NOT IN 
(SELECT Max(ID)
 FROM [table1]
 GROUP BY [col1], [col2], [col3]
 HAVING COUNT([col2])>1);

Duane
Hook'D on Access
MS Access MVP
 
Works perfectly with a small amount of data. However, when I try to CurrentDb.Execute the statement on large amount of data Access freezes.
 
This should be less slow:
Code:
DELETE *
FROM [table1]
WHERE ID NOT IN 
(SELECT Max(ID)
 FROM [table1]
 GROUP BY [col1], [col2], [col3])

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
And what about this ?
Code:
DELETE * FROM table1 A
WHERE ID <> (SELECT Max(ID) FROM table1
 WHERE col1=A.col1 AND col2=A.col2 AND col3=A.col3)

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top