Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd do this in multiple steps. Large delete operations done in a single step make me too nervous -- what if you make a mistake? There's no sql 'undo' statement.</p> <pre><code>-- Setup the data DROP Table foo; DROP Table bar; DROP Table bat; DROP Table baz; CREATE TABLE foo ( id int(11) NOT NULL, SchemeName varchar(50), SchemeNumber varchar(15), PRIMARY KEY (id) ); insert into foo values (714, 'Malcolm', 'ABC123' ); insert into foo values (80, 'Malcolm', 'ABC123' ); insert into foo values (96, 'Malcolms Scheme', 'ABC123' ); insert into foo values (101, 'Malcolms Scheme', 'ABC123' ); insert into foo values (98, 'Malcolms Scheme', 'DEF888' ); insert into foo values (654, 'Another Scheme ', 'BAR876' ); insert into foo values (543, 'Whatever Scheme ', 'KJL111' ); -- Find all the records that have dups, find the longest one create table bar as select max(length(SchemeName)) as max_length, SchemeNumber from foo group by SchemeNumber having count(*) &gt; 1; -- Find the one we want to keep create table bat as select min(a.id) as id, a.SchemeNumber from foo a join bar b on a.SchemeNumber = b.SchemeNumber and length(a.SchemeName) = b.max_length group by SchemeNumber; -- Select into this table all the rows to delete create table baz as select a.id from foo a join bat b where a.SchemeNumber = b.SchemeNumber and a.id != b.id; </code></pre> <p>This will give you a new table with only records for rows that you want to remove.</p> <p>Now check these out and make sure that they contain only the rows you want deleted. This way you can make sure that when you do the delete, you know exactly what to expect. It should also be pretty fast.</p> <p>Then when you're ready, use this command to delete the rows using this command.</p> <pre><code>delete from foo where id in (select id from baz); </code></pre> <p>This seems like more work because of the different tables, but it's safer probably just as fast as the other ways. Plus you can stop at any step and make sure the data is what you want before you do any actual deletes.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload