Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update records that satisfies a condition with incrementing number

Tags:

sql

postgresql

I have a table in postgres like this:

Id    Name    local_site_id    local_id
1     A       2                
2     B       2
3     C       1
4     D       2
5     E       1

How do I update the table into this using SQL query:

Id    Name    local_site_id    local_id
1     A       2                1
2     B       2                2
3     C       1                
4     D       2                3
5     E       1                

Right now, the local_id field is empty for all the records. I want to update the local_id values with an incrementing number starting from 1 only for rows that have local_site_id=2 Is it possible using SQL?

like image 357
Harish Kayarohanam Avatar asked Feb 20 '23 13:02

Harish Kayarohanam


2 Answers

That's a typical use case for the row_number() window function. Assuming your main table is T, this query should work with postgresql 8.4 or newer:

update T set local_id=s.rn 
from (select id,row_number() over(order by id) as rn from T where local_site_id=2) s
 where T.id=s.id;
like image 59
Daniel Vérité Avatar answered Feb 25 '23 10:02

Daniel Vérité


I believe this should do what you want, let me know otherwise:

UPDATE table_name
SET    local_id = row
FROM
(
    SELECT *, 
           ROW_NUMBER() OVER (PARTITION BY local_site_id ORDER BY name) AS row
    FROM   table_name
    WHERE  local_site_id = 2
) AS Q
WHERE Q.id = table_name.id;
like image 29
XN16 Avatar answered Feb 25 '23 10:02

XN16