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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted Nov 16, 2011, 2:25 AM
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
Pravin MorePosted Nov 16, 2011, 1:37 AM
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.
AartiPosted Nov 16, 2011, 12:32 AM
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.
dev 0Posted Nov 15, 2011, 11:53 PM
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
Vineet Kumar SainiPosted Nov 15, 2011, 4:23 PM
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..
Javeed M ShaikhPosted Nov 15, 2011, 1:24 PM
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.