sqlrangeidiomsmonetdbiota

SQL statement to generate a column whose value is the record index


I have some SQL table, say with a single column c1:

c1
10
3
1
10
5

Now, I'd like to issue an SQL command (not some operation of my DBMS, which I have intentionally not mentioned) which causes my table to be:

c1 record_index
10 0
3 1
1 2
10 3
5 4

Very simple... can this be done? Obviously, you don't know in advance the length of the table, so no SQL insertion or similar tricks.

Note: I'd like a general answer, but to be specific - I'm working with MonetDB.


Solution

  • Inspired by @a_horse_with_no_name 's answer...:

    SELECT 
      c1, 
      row_number() OVER (ORDER BY dummy)-1 AS record_index
    FROM 
      (SELECT 
        c1,
        42 AS dummy 
      FROM t1
    ) AS t1_augmented;
    

    (Noting of course that row_number()'s result is 1-based.)