michael michael - 2 months ago 6
SQL Question

SQL: Add column with incremental id to SELECT

I have simple query like:

SELECT name FROM people;


people
table not have unique id column. I want to add to the query result column
id
with incremental
int
starting from 0/1 doesn't matter. How to achieve this? (postgresql DB)

Answer

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;