1

I have a table which contains 69000 records. Now, how to add a new column(say index) which should contain the value 1 for 1st row, 2 for 2nd row ....etc.

I want the following result

   id      name      index
 --------------------------
 9796896   sandy       1
 796869    raj         2
4
  • You can add the new column as IDENTITY column. Commented Sep 6, 2019 at 9:52
  • Why have you tagged this with Oracle if you are using PostgreSQL? (Also 'index' seems like a poor choice name for a column... it wouldn't be legal in Oracle, unless quoted.) Commented Sep 6, 2019 at 9:58
  • Possible duplicate of PostgreSQL Autoincrement Commented Sep 6, 2019 at 10:19
  • Check this out tutorialspoint.com/postgresql/… Commented Sep 6, 2019 at 10:33

4 Answers 4

3

Add the column and update it with something like that :

with cte as
(
   select *
       , rank() over (order by id desc) as ranker
   from test
)
update test
   set index = ranker
from cte
where cte.id = test.id;
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

ALTER TABLE Tablename
    ADD COLUMN index int               
        GENERATED BY DEFAULT AS IDENTITY;

1 Comment

generated columns ? Are they not available only for version 12 ?
0

you can use identity column of the oracle:

alter table your_Table add index_ number GENERATED by default as IDENTITY;

also, you can add the column and then assign value to it:

alter table your_Table add index_ number;

update your_Table tt
set tt.index_  =  (select rn from (
select row_number() over (order by id desc) rn
from your_Table t
) t where t.id = tt.id)

Cheers!!

Comments

0

This worked nicely for me running postgres 9.6:

ALTER TABLE test ADD COLUMN index BIGSERIAL ;

Short one liner and it keeps on auto-incrementing in future inserts.

Although I think the count started at zero. I'll update answer after I checked.

Comments

Your Answer

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.