SRobertJames
SRobertJames

Reputation: 9208

Numbering all rows by an order

I have a table with a two column PK. I'd like to add a new column, nid, which numbers each row (1,2,3...), based on a particular ORDER BY.

So:

x | y | z
3   7   2
1   4   1

When numbered by z ASC becomes:

x | y | z | nid
3   7   2 | 2
1   4   1 | 1

Can I do this in SQL (Postgres 9.4)?

Upvotes: 0

Views: 58

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

If I understand correctly, you can just use row_number():

select x, y, z, row_number() over (order by z) as nid
from t;

Upvotes: 2

Related Questions