Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Add column with incremental id to SELECT

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)

like image 875
michael Avatar asked Sep 12 '15 13:09

michael


People also ask

How do you add an incremental number field in SQL?

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) .

How do you add sequential numbers in SQL?

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.

How can change column auto increment in SQL Server?

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.


2 Answers

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;
like image 185
Lukasz Szozda Avatar answered Oct 08 '22 01:10

Lukasz Szozda


The row_number window function should fit the bill:

SELECT ROW_NUMBER() OVER (ORDER BY 1), *
FROM   people
like image 35
Mureinik Avatar answered Oct 08 '22 00:10

Mureinik