2

I have a table on PostgreSQL and 1000 rows in it. I have an integer column in my table that is empty. I want to populate newid with sequential, unique numbers a bit like a primary key.

Product
-------------------------
id  name  newid  size
60   ....  null   L
72   ....  null   M
83   ....  null   xl
84   ....  null   S
85   ...

How can I write a query that update my newid column.

Product
-------------------------
id  name  newid  size
60   ....  1      L
72   ....  2      M
83   ....  3      xl
84   ....  4      S
85   ...
6
  • 1
    Please elaborate. It is unclear what you are trying to do. Sample data and desired results can be a big help. Commented Jun 22, 2015 at 11:17
  • What's wrong with the id column? Commented Jun 22, 2015 at 11:19
  • newid column will be generated new integer values . Commented Jun 22, 2015 at 11:22
  • 3
    Are you looking for ROW_NUMBER() ? Commented Jun 22, 2015 at 11:22
  • Why should the value L get number 1 and value M the number 2? Commented Jun 22, 2015 at 11:26

2 Answers 2

8

You can do this using JOIN or subquery. The idea is to calculate the new id using row_number() and then bring that value into each row:

with newvals (
      select p.*, row_number() over (order by id) as seqnum
      from product p
     )
update product p
    set newid = (select seqnum from newvals nv where nv.id = p.id);
Sign up to request clarification or add additional context in comments.

Comments

2

How about:

update mytable set
newid = id + 1000000

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.