PostgreSQL: list the result of a SQL query

Consider the following SQL query and response:

CREATE TEMPORARY TABLE dreams (name text, type text);
INSERT INTO dreams VALUES ('Monkey', 'nice');
INSERT INTO dreams VALUES ('Snake', 'Not nice');
INSERT INTO dreams VALUES ('Donkey', 'nice');
INSERT INTO dreams VALUES ('Bird', 'nice');

SELECT name from dreams WHERE type='nice' ORDER BY name;
  name
--------
 Bird
 Donkey
 Monkey
(3 rows)

      

I would like to list the results in the order of appearance, regardless of any existing ids, for convenience. The expected output should be something a-la:

SELECT <magic_enumeration>, name from dreams WHERE type='nice' ORDER BY name;

 magic_enumeration |  name
-------------------+--------
 1                 | Bird
 2                 | Donkey
 3                 | Monkey
(3 rows)    

      

Any ideas on how to list the query result in order of appearance?

+3


source to share


1 answer


Try using row_number which is a window function



SELECT row_number() OVER (ORDER BY name) sid, <-- magic enumeration!
       name 
  FROM dreams 
  WHERE type='nice' 
  ORDER BY name;

      

+5


source







All Articles