2

My talbe article_favorites did not have row number, right now it contains 100000 record. I want to add a bigint id column in the talbe and set the id as row number by default. I tried this sql:

update article_favorites set id = row_number() OVER ()

but it tell me the window functions are not allowed in UPDATE, what should I do to update the id as row number?

asked Dec 11, 2021 at 14:43

3 Answers 3

6

Using a sequence might be faster than using row_number()

create sequence id_seq;
update article_favorites 
 set id = nextval('id_seq');
drop sequence id_seq;
answered Dec 11, 2021 at 17:32
1
  • I guess we should use a temp sequence here: CREATE TEMP SEQUENCE .. which will be dropped automatically, just in case. Commented Jun 21, 2023 at 14:51
1

As the error you're encountering mentions, window functions can't be used in an UPDATE statement BUT you can define them ahead of time in a CTE or subquery, and use their evaluated results in the UPDATE statement. IF you have a unique way to identify the row already, then you can accomplish your goal like so:

WITH _article_favorites_rowids AS
(
 SELECT uniqueField, ROW_NUMBER() OVER () AS newId
 FROM _article_favorites
)
UPDATE a
SET a.id = r.newId
FROM _article_favorites a
INNER JOIN _article_favorites_rowids r
 ON a.uniqueField = r.uniqueField
answered Dec 11, 2021 at 15:13
3
  • uniqueField is usually the id, so it is hard to use another uniqueField, and I don't think we can use window functions in where clauses or join conditions. Any ideas if we don't have a usable uniqueField to link the data for the update? Commented Jun 21, 2023 at 14:49
  • @Rafs I don't follow. Does your data have a uniqueField? Commented Jun 22, 2023 at 3:32
  • No, no other unique fields apart from id Commented Jun 26, 2023 at 8:23
0

You can add generated values when you create id column. The statement below creates a auto generated column and fills if for existing records.

ALTER TABLE article_favorites ADD id bigserial;

You can create primary key if your table does not have one or you can just add unique key to that field.

ALTER TABLE article_favorites ADD id bigserial PRIMARY KEY; -- or UNIQUE 

You can use smallserial or serial (represent integer data type) instead of bigserial (bigint data type). These types are not true types. here is document link related.

answered Dec 12, 2021 at 23:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.