PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

SQL:Spalte mit inkrementeller ID zu SELECT hinzufügen

Verwenden Sie ROW_NUMBER() :

SQLFiddle

SELECT 
  name,
  ROW_NUMBER() OVER (ORDER BY name) AS id
FROM people;

BEARBEITEN:

Unterschied zwischen 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)

Im zweiten Fall gibt es keine Sortieroperation.

Sie können die zweite Abfrage auch schreiben als:

SELECT 
    name,
    ROW_NUMBER() OVER () AS id
FROM people;

Warum Leute ORDER BY 1 schreiben in Fensterfunktionen?

Denn in manchen Dialekten ist es erforderlich und ORDER BY 1 verhält sich wie ein Platzhalter.

Orakel:

SELECT 
  name,
  ROW_NUMBER() OVER (ORDER BY 1) AS id
FROM people;

TSQL:

SELECT 
    name,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS id
FROM people;