Search code examples
postgresqlduplicatessql-delete

How to delete only one row from non unique set of rows in Postgres?


I have this table

create table order_details(
    id_of_product integer,
    id_of_person text
)

both fields are not unique. How to delete one row from the table with specified id_of_product and id_of_person

for example i need to delete one row with id of 6 P.S person is the same for this set of rows

sample data


Solution

  • You can use system column ctid to specify particular row, even if it has no unique values.

    WITH u AS 
    (
        SELECT distinct on (id_of_product, id_of_person) id_of_product, id_of_person, ctid 
        FROM order_details
    )
    DELETE FROM order_details 
    WHERE id_of_product=6 AND id_of_person='ey...' AND ctid IN (SELECT ctid FROM u)