Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate sequence numbers on PostgreSQL integer column

Tags:

sql

postgresql

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   ...
like image 347
barteloma Avatar asked Mar 17 '26 02:03

barteloma


1 Answers

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);
like image 65
Gordon Linoff Avatar answered Mar 19 '26 16:03

Gordon Linoff