1

Im trying to update the duplicate usernames in my PostgreSQL database by adding a number at the end of the duplicates. curently my users table is as follows:

| user_id | username |
|---------|----------|
| 1       | mike     |
| 2       | mike     |
| 3       | susan    |
| 4       | susan    |
| 5       | susan    |
| 6       | joe      |

And the expected result is:

| user_id | username |
|---------|----------|
| 1       | mike     |
| 2       | mike2    |
| 3       | susan    |
| 4       | susan2   |
| 5       | susan3   |
| 6       | joe      |

I've been trying to use some expressions found here in StackOverflow but i keep getting a SQL syntax error.

1 Answer 1

5

You can update from a sub-query:

update users
   set username = concat(t.username, t.rn)
from (
  select user_id, username, 
         row_number(*) over (partition by username order by user_id) as rn
  from users
) t
where t.user_id = users.user_id
  and t.rn > 1;

Online example

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

Comments

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.