HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

PostgreSQL - Create view with autoincremental column

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlcreatecolumnwithviewautoincremental

Problem

I have a PostgreSQL table, and I need to create a view with a new column. This column needs to be an auto-incremental column starting at 1 and going to N.

Is this possible to do without effecting the original schema of the legacy data structure?

Solution

You can use row_number, and the easiest way is to just add a

row_number() OVER ()


field into the view. You need the PARTITION BY and using the "true" expression is the most performant way (no need for sorting like in Fabrizio Mazzoni's answer).

Update: Also no need to partition by true, just use () as the "over" expression.

Code Snippets

row_number() OVER ()

Context

StackExchange Database Administrators Q#56897, answer score: 21

Revisions (0)

No revisions yet.