SQL: Add column with incremental id to SELECT

前端 未结 4 2346
迷失自我
迷失自我 2021-02-19 03:57

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 r

相关标签:
4条回答
  • 2021-02-19 04:49

    Check out the row_number() function at https://www.postgresql.org/docs/current/static/functions-window.html

    0 讨论(0)
  • 2021-02-19 04:51

    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;
    
    0 讨论(0)
  • 2021-02-19 04:54

    The row_number window function should fit the bill:

    SELECT ROW_NUMBER() OVER (ORDER BY 1), *
    FROM   people
    
    0 讨论(0)
  • 2021-02-19 04:54

    If you need it only when the query is run, you can use row_number.

    select row_number() over(order by name) as id, name
    from people
    
    0 讨论(0)
提交回复
热议问题