1

I have user tables and now I want to add one serial column cid:

user:

 id    | username | email           | createdAt
-------------------------------------------------
"uuid" | "abc"    | "[email protected]" | '2017-01-01'
"uuid" | "abc"    | "[email protected]" | '2017-02-01'
"uuid" | "abc"    | "[email protected]" | '2017-03-01'

I want to add a column cid with values like serial but not primary key

  id   |username|     email       | createdAt    | cid
-------------------------------------------------------
"uuid" | "abc"  | "[email protected]" | '2017-01-01' |  1
"uuid" | "abc"  | "[email protected]" | '2017-02-01' |  2
"uuid" | "abc"  | "[email protected]" | '2017-03-01' |  3
...

What I tried:

alter table user add column cid serial not null;

but it generates:

  id   |username|     email       | createdAt    | cid
-------------------------------------------------------
"uuid" | "abc"  | "[email protected]" | '2017-01-01' | 4
"uuid" | "abc"  | "[email protected]" | '2017-02-01' | 7
"uuid" | "abc"  | "[email protected]" | '2017-03-01' | 3
....

can I do something like:

alter table user add column cid serial not null order by createdAt

So that it can generate the expected result which is cid sequential values with order by createdAt?

1 Answer 1

1

Why add it to the table? You can just do:

select u.*, row_number() over (order by u.createdAt) as seqnum
from user u;

If you have an index on user(createdAt), then this should take advantage of the index.

If you have a unique column on the table, you can do an update:

update user u set cid = uu.seqnum from (select u.*, row_number() over (order by u.createdAt) as seqnum from user u ) uu on u.uuid = uu.uuid

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for giving a quick answer.....yes I have to add the column as my id column is an uuid so need a seperate column which has a sequential number
I also tried update user set cid = row_number() over (order by user.createdAt) but throwing error

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.