Updated on 2026-10-21 GMT+08:00

How Do I Delete Duplicate Rows?

Answer: You can use either of the following methods:

  • Method 1:
    -- Create a table and insert data into the table.
    gaussdb=#CREATE TABLE tbl_del(c1 varchar,c2 int);
    gaussdb=#INSERT INTO tbl_del VALUES ('a',1),('a',1);
    gaussdb=#INSERT INTO tbl_del VALUES ('b',2),('b',2);
    gaussdb=#INSERT INTO tbl_del VALUES ('c',3);
    
    -- Query the deduplicated data.
    gaussdb=#SELECT distinct * FROM tbl_del;
     c1 | c2 
    ----+----
     b  |  2
     a  |  1
     c  |  3
    (3 rows)
    
    -- Run the following SQL statements to delete duplicate data:
    gaussdb=#DELETE FROM tbl_del t1 WHERE ctid <>(
        SELECT max(ctid) FROM tbl_del t2 WHERE t1.c1 = t2.c1
    );
    
    -- Query data.
    gaussdb=#SELECT * FROM tbl_del;
     c1 | c2 
    ----+----
     a  |  1
     b  |  2
     c  |  3
    (3 rows)
    
    -- Drop.
    gaussdb=#DROP TABLE tbl_del;
  • Method 2:
    -- Create a table and insert data into the table.
    gaussdb=#CREATE TABLE tbl_del(c1 varchar,c2 int);
    gaussdb=#INSERT INTO tbl_del VALUES ('a',1),('a',1);
    gaussdb=#INSERT INTO tbl_del VALUES ('b',2),('b',2);
    gaussdb=#INSERT INTO tbl_del VALUES ('c',3);
    
    -- Query the deduplicated data.
    gaussdb=#SELECT distinct * FROM tbl_del;
     c1 | c2 
    ----+----
     b  |  2
     a  |  1
     c  |  3
    (3 rows)
    
    -- Copy the tbl_del2 table.
    gaussdb=#CREATE TABLE tbl_del2 AS SELECT * FROM tbl_del;
    
    -- Clear the tbl_del table and insert the deduplicated data into the table.
    gaussdb=#TRUNCATE TABLE tbl_del;
    gaussdb=#INSERT INTO tbl_del SELECT distinct * FROM tbl_del2;
    
    -- Query.
    gaussdb=#SELECT * FROM tbl_del;
     c1 | c2 
    ----+----
     b  |  2
     a  |  1
     c  |  3
    (3 rows)
    
    -- Drop.
    gaussdb=#DROP TABLE tbl_del,tbl_del2;