Hi,
Suppose DataBase table has no primary key. How can we delete duplicate rows from table. What will be SQL statement?
Thanks.
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Javeed M ShaikhRank #839 · 2.7K reputationPosted Nov 15, 2011, 8:24 AM EST
SELECT distinct A.id
FROM table1 As A
INNER JOIN table1 As B On (A.id = B.parentId);
if it looks good than issue the delete for the same condition.
Vineet Kumar SainiRank #257 · 9.8K reputationPosted Nov 15, 2011, 11:23 AM EST
Please visit this link for your problem
http://stackoverflow.com/questions/985384/delete-duplicate-records-from-a-sql-table-without-a-primary-key
http://www.simple-talk.com/sql/t-sql-programming/removing-duplicates-from-a-table-in-sql-server/
Thanks..
dev 027 reputationPosted Nov 15, 2011, 6:53 PM EST
As you mentioned without primary key in table, you can try below code,
select * from temp_t ;
select name, COUNT(name) as c, max(id) as m into #temp_new from temp_t group by name having COUNT(name) >1;
select * from temp_t where id not in (select m from #temp_new ) order by name;
Hope this will help you .
Thanks
AartiRank #2,383 · 594 reputationPosted Nov 15, 2011, 7:32 PM EST
Please Check with below Sql to get duplicate rows according your question.
create
table #DuplicateTable (id int,name varchar(20));insert
into #DuplicateTable values(1,'a') ;insert
into #DuplicateTable values(1,'a') ;insert
into #DuplicateTable values(2,'b') ;insert
into #DuplicateTable values(3,'c') ;insert
into #DuplicateTable values(4,'d') ;insert
into #DuplicateTable values(4,'d') ;insert
into #DuplicateTable values(1,'e') ;select
* from #DuplicateTable----------------------------------------------
SELECT
*INTO #duplicatedata FROM #DuplicateTableGROUP
BY ID,nameHAVING
COUNT(*) > 1select
* from #duplicatedata-------------------------
-- now use below sql to delete duplicate rows
DELETE
FROM #DuplicateTableFROM
#DuplicateTableINNER
JOIN #duplicatedataON
#DuplicateTable.ID = #duplicatedata.IDAND
#DuplicateTable.Name = #duplicatedata.Name------select again main table and see duplicates deleted r not
select * from #DuplicateTable
select * from #Duplicatedata
Thanks.
Pravin MoreRank #1,419 · 1.2K reputationPosted Nov 15, 2011, 8:37 PM EST
do simple steps......
step1.select Distinct a.* into temp1 from tablename a
step2. delete from tablename
step3. insert temp1 to tablename like insert into tablename(column1,column2....) select * from temp1
Thanks,
Pravin.
Satyapriya NayakRank #47 · 31.5K reputationPosted Nov 15, 2011, 9:25 PM EST
STEP 1 - Insert your distinct data into a temporary table select distinct* into temp from TableName
STEP 2 - Delete From TableName
STEP 3 - Insert TableName Select * From temp
Thanks