This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes JDBC and the fly likes delete duplicate records Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "delete duplicate records" Watch "delete duplicate records" New topic
Author

delete duplicate records

vikas sharmaa
Ranch Hand

Joined: Jun 28, 2007
Posts: 191
i've an APR_MGR table with columns as mgr_id, flag, and backupid. thr is no primary key constraints in the table. the data is like below:

MgrID flag backupid
101 N null
101 N null
101 N null
102 Y 1111
103 Y 2222

now, i wud like to write a delete query, that will delete all the duplicate records of MgrID 101, except the first one.

i've written the below query:

delete from APR_MGR where MgrID = 101 and flag = 'N' and 1 < (select count(MgrID) from APR_MGR where MgrID = 101 and flag = 'N')

i was expecting 2 records to be deleted of MgrID 101, but it deleted all the 3 records.

what shall be the correct query?
[ August 30, 2008: Message edited by: vikas sharmaa ]
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30789
    
157

Vikas,
What database are you using? If it is one that supports the concept of a row number, you can write a query that keeps the "first" one intact.

If it does not support the concept of a row number, the procedure is more steps. You will have to copy the distinct records into a new table, delete all the records from this table and then copy the records back into this table.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
vikas sharmaa
Ranch Hand

Joined: Jun 28, 2007
Posts: 191
i m using oracle 9i. then what shall be the delete query?
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1134

Vikas,
This has nothing to do with JDBC of-course :-)
(NOTE: Untested - and check the syntax also :-)

Good Luck,
Avi.
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30789
    
157

Vikas,
It's easier to do this in Oracle than some other databases so this is good. See this wiki page sql for an example.

It's ok the question isn't about JDBC. It is about SQL making it on topic.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: delete duplicate records