Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL update records with ROW_NUMBER()

Tags:

sql

postgresql

I have a table called 'cards', which has a column called 'position' How can I update/set the 'position' to equal the row number of each record, using ROW_NUMBER()?

I am able to query the records and get the correct values using this statement:

"SELECT *,  ROW_NUMBER() OVER () as position FROM cards"

So, I would like to do this but have it update the new values in the database.

like image 484
John.Mazzucco Avatar asked Dec 09 '16 22:12

John.Mazzucco


People also ask

Can we use Rownum in update query?

You cannot use the NAME column to sort! UPDATE (SELECT name, order_id FROM test1 ORDER BY order_id) SET order_id = ROWNUM; Does not produce the expecting result because the order by is not used.

What is ROW_NUMBER () function in SQL?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.


2 Answers

Let me assume that cards has a primary key. Then you can use join:

update cards c
    set position = c2.seqnum
    from (select c2.*, row_number() over () as seqnum
          from cards c2
         ) c2
    where c2.pkid = c.pkid;

I should note that the over () looks strange but Postgres does allow it. Normally an order by clause would be included.

like image 138
Gordon Linoff Avatar answered Sep 21 '22 08:09

Gordon Linoff


Original question was tagged with SQLite. Starting from SQLite 3.25.0 we could natively use ROW_NUMBER.

CREATE TABLE cards(pk INT PRIMARY KEY, c VARCHAR(2), seq INT);
INSERT INTO cards(pk, c) VALUES (10,'2♥'),(20,'3♥'),(30, '4♥');

WITH cte AS (SELECT *, ROW_NUMBER() OVER() AS rn FROM cards)
UPDATE cards SET seq = (SELECT rn FROM cte WHERE cte.pk = cards.pk);

SELECT * FROM cards;

enter image description here

Exactly the same code will work with PostgreSQL too: Rextester Demo

like image 42
Lukasz Szozda Avatar answered Sep 17 '22 08:09

Lukasz Szozda