1

I want to add e-mails numbered from 1 to 100. So effectively I want to do something like:

tmp := 0
update user SET tmp = tmp + 1, email = 'test' || TO_CHAR(tmp,'fm00000') || '@example.com'
    where removed = false
    ORDER BY id
    limit 100;

And preferably would like it to work in 8.3. Note - I cannot use ids as they are not from 1 to 100 in the selected rows.

Edit: Forgot I'm on 8.3...

2
  • if you want to ADD values, you must use INSERT, not UPDATE Commented Jul 29, 2014 at 12:39
  • @a_horse_with_no_name Thanks. I got it crossed over with the other question about (name, id) counters. Commented Jul 29, 2014 at 14:59

1 Answer 1

2

You don't need a hack with variables in Postgres. Just use a window function. Unfortunately window functions cannot be used directly in an UPDATE statement, but this can easily be combined with a CTE:

with numbered_users as (
   select id, 
          row_number() over (order by email) as rn
   from users
   where removed = false
) 
update users 
  set email = 'test' || TO_CHAR(nu.rn,'fm00000') || '@example.com'
from numbered_users nu
where rmoved = false
  and users.id = nu.id;

This assumes the id column is unique

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

4 Comments

I guess that would work, but I could not update to 8.4 and stuck on 8.3 on that server... But create temp sequence tmp; Works fine :-).
@Nux: you should have mentioned that you are using an outdated and un-supported version. Plus: you shouldn't upgrade to 8.4 either - that is also end-of-life. If you upgrade go straight to 9.3 (or even 9.4 depending on when you do it)
Unfortunately they broke compatibility on 8.4 and I was not able to upgrade because of one old application. I'm aware that 8.x is not supported. Thanks for your effort anyway.
@Nux: they didn't "break compatibility" in 8.4. They just enforced some rules more strictly than before. All the casts that were removed in 8.4 have always been discouraged in earlier releases. Plus: relying on implicit data type conversion (which is what you did when your code breaks with 8.4) is bad coding style any DBMS not just Postgres.

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.