user558122
user558122

Reputation: 861

PostgreSQL Record Reordering using Update with a Sub-Select

I found this solution on the SQL Server forum on how to reorder records in a table.

UPDATE SomeTable
SET rankcol = SubQuery.Sort_Order
FROM
    (
    SELECT IDCol, Row_Number() OVER (ORDER BY ValueCOL) as SORT_ORDER
    FROM SomeTable
    ) SubQuery
INNER JOIN SomeTable ON
SubQuery.IDCol = SomeTable.IDCol

When I try doing the same on PostgreSQL, I get an error message -

ERROR: table name "sometable" specified more than once

Any help will be appreciated.

Thanks!

Upvotes: 2

Views: 2740

Answers (1)

maniek
maniek

Reputation: 7307

You don`t need to explicitly join SomeTable, how cool is that? :)

UPDATE SomeTable
SET rankcol = SubQuery.Sort_Order
FROM
    (
    SELECT IDCol, Row_Number() OVER (ORDER BY ValueCOL) as SORT_ORDER
    FROM SomeTable
    ) SubQuery
where SubQuery.IDCol = SomeTable.IDCol

remark: Postgres is case insensitive, better use lower-case, like row_number, sort_order, id_col , etc.

Upvotes: 5

Related Questions