I have a simple query like:
SELECT name FROM people;
The people
table does not a have unique id column. I want to add to the query result a column id
with incremental int
starting from 0 or 1 (it doesn't matter). How can one achieve this? (postgresql DB)
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .
To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row.
If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.
Use ROW_NUMBER()
:
SQLFiddle
SELECT
name,
ROW_NUMBER() OVER (ORDER BY name) AS id
FROM people;
EDIT:
Difference between ORDER BY 1
vs ORDER BY column_name
SQLFiddleDemo
SELECT
name,
ROW_NUMBER() OVER (ORDER BY name) AS id
FROM people;
/* Execution Plan */
QUERY PLAN WindowAgg (cost=83.37..104.37 rows=1200 width=38)
-> Sort (cost=83.37..86.37 rows=1200 width=38)
**Sort Key: name**
-> Seq Scan on people (cost=0.00..22.00 rows=1200 width=38)
SELECT
name,
ROW_NUMBER() OVER (ORDER BY 1) AS id
FROM people;
/* Execution Plan */
QUERY PLAN WindowAgg (cost=0.00..37.00 rows=1200 width=38)
-> Seq Scan on people (cost=0.00..22.00 rows=1200 width=38)
In second case there is no sort operation.
You can also write second query as:
SELECT
name,
ROW_NUMBER() OVER () AS id
FROM people;
Why people write ORDER BY 1
in windowed functions?
Because in some dialects it is required and ORDER BY 1
acts like placeholder.
Oracle:
ORA-30485: missing ORDER BY expression in the window specification
SELECT
name,
ROW_NUMBER() OVER (ORDER BY 1) AS id
FROM people;
TSQL:
The function 'ROW_NUMBER' must have an OVER clause with ORDER BY.
SELECT
name,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS id
FROM people;
The row_number
window function should fit the bill:
SELECT ROW_NUMBER() OVER (ORDER BY 1), *
FROM people
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With