1

-- Create the table CREATE TABLE colour ( col1 VARCHAR, col2 VARCHAR, col3 VARCHAR );

-- Insert sample data INSERT INTO colour (col1, col2, col3) VALUES ('red', 'blue', 'black'), ('grey', 'red', 'white'), ('pink', NULL, 'blue'), ('red', 'blue', 'black'), ('grey', 'red', 'white'), ('pink', NULL, 'blue');

In PostgreSQL, I want to delete exact duplicate rows from the table and only want to keep one of them. What would you suggest to me?

I tried using CTE but not get the required result.

1 Answer 1

0

You can try something like this:

WITH duplicates AS (
SELECT
    ctid,
    ROW_NUMBER() OVER (PARTITION BY col1, col2, col3 ORDER BY ctid) AS rn
FROM
    colour
 )
DELETE FROM colour
WHERE ctid IN (
SELECT ctid
FROM duplicates
WHERE rn > 1
);

First you have to find the duplicated rows, and use the internal field ctid in the CTE to identify the rows you want to delete

Sign up to request clarification or add additional context in comments.

1 Comment

If the above answer resolved your issue, or lead you to the solution, then kindly accept it. This aids future users having the same or similar issue and removes it from the unanswered queue. Please do not leave a successfully answered question as unanswered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.