Home > Net >  How to delete all rows from table except 6 given known uuids with PostgreSQL
How to delete all rows from table except 6 given known uuids with PostgreSQL

Time:03-26

I want to clean a table and only keep 6 rows targeted with uuids

DELETE FROM user WHERE user_id!='2536466f-38d0-4e81-acda-2e411fdb3030'
AND user_id!='cefc6515-e4a4-460c-9fb2-eb883037ff9e'
AND user_id!='479acacf-3914-485f-958c-51sfe77e6beb'
AND user_id!='7436a5a6-1361-42df-81a3-63007afcb835'
AND user_id!='373d4006-2f91-470f-b256-195fsd5835e9'
AND user_id!='aaff2a33-2a75-4e65-a7re-658cb38e6549'

I also tried this variation without success:

DELETE FROM user WHERE EXISTS(
    SELECT FROM user WHERE user_id!='2536466f-38d0-4e81-acda-2e411fdb3030'
AND user_id!='cefc6515-e4a4-460c-9fb2-eb883037ff9e'
AND user_id!='479acacf-3914-485f-958c-51sfe77e6beb'
AND user_id!='7436a5a6-1361-42df-81a3-63007afcb835'
AND user_id!='373d4006-2f91-470f-b256-195fsd5835e9'
AND user_id!='aaff2a33-2a75-4e65-a7re-658cb38e6549'
    )

Is there anyway to achieve this?

CodePudding user response:

You can use NOT IN.

The AND in your WHERE clause doesn't work as the uuids can be at the same time in all rows.

DELETE FROM user 
WHERE  user_id NOT IN (
    '2536466f-38d0-4e81-acda-2e411fdb3030' ,
    'cefc6515-e4a4-460c-9fb2-eb883037ff9e' ,
    '479acacf-3914-485f-958c-51sfe77e6beb' ,
    '7436a5a6-1361-42df-81a3-63007afcb835' ,
    '373d4006-2f91-470f-b256-195fsd5835e9' ,
    'aaff2a33-2a75-4e65-a7re-658cb38e6549'
) ;
  • Related