SQL Tips #31 - Deleting Duplicate Entries While Keeping the Original


Friday, 7 December 2018

Duplicate rows happen - this query deletes duplicate entries from a table while keeping the original (proto) entry.

The Query

delete FROM tblBookingComment WHERE commentid in (
SELECT commentid FROM (
    SELECT 
        (SELECT top 1 commentid FROM tblBookingComment 
        WHERE addedby=1 and bookingid=comments.bookingid and comment=comments.comment) as protocomment,* 
        FROM tblBookingComment as comments WHERE addedby=1 and 
        (select count(*) from tblBookingComment where addedby=1 
        AND bookingid=comments.bookingid and comment=comments.comment
        group by bookingid, comment) > 1
    and commentid <> (
                            SELECT top 1 commentid 
                            FROM tblBookingComment 
                            WHERE bookingid=comments.bookingid and comment=comments.comment
                           )
    ) as t
)

Disclaimer

These queries are provided as a guide, and are by no means perfect. I didn't write all of these - many are collated from MSDN documentation and community sources over the years.

Tags

SQL, Programming
Share with: 

Useful SQL tips - how to delete duplicate entries in a table while keeping the original


Support this Site

Buy me a coffee

Developer Courses

Pluralsight - Hardcore Developer and IT Training
Skype Web SDK: Getting Started
Skype Web SDK: Audio & Video

Popular Articles

What is Kutamo?
Kilimanjaro Climb
Kilimanjaro 2015
Kilimanjaro 2013
Australian Postcodes
New Zealand Postcodes
Worldwide City Database

Favourite Links

Kilimanjaro Climbs
Kutamo Studios
Kutamo Meetings
Litzi
ErrLog.IO
Kutamo

Tags / Keywords

SQL, Programming