I have a table in Postgres with a column that has distinct alphanumeric values in the pattern 1234P001. However, due to some bug, there are duplicate values in the column, like 1234P001
appearing thrice.
I want to replace duplicate 1234P001
‘s with 1234P002
, 1234P003
and 1234P004
. How can I do this in PostgresSql?
I tried using sequence but it didn’t work.
2
Answers
This can be done with a temporary table and the use of
row_number
window function. Here is an illustration.Using this sample data to illustrate the concept
First you need to identify the duplicated key – use
count .. over
Assign each duplicated row a unique sequence number (you’ll see soon why)
Now generate all not existing keys based on you key schema (here prefix of length 5 and 3 digit integer)
In the last step simple join the table with duplicated keys with the unassigned key using teh unique index to get the resolution
old_id
and the uniquenew_id
Note I use an outer join – if you get an empty
new_id
there is a problem you have no free key to fix in your schema.