22

I was wondering if it would be possible to enumerate returned rows. Not according to any column content but just yielding a sequential integer index. E.g.

select ?, count(*) as usercount from users group by age

would return something along the lines:

1    12
2    78
3     4
4    42

it is for https://data.stackexchange.com/

Cœur
  • 37,241
  • 25
  • 195
  • 267
SilentGhost
  • 307,395
  • 66
  • 306
  • 293

7 Answers7

25

try:

SELECT
    ROW_NUMBER() OVER(ORDER BY age) AS RowNumber
        ,count(*) as usercount 
    from users 
    group by age
KM.
  • 101,727
  • 34
  • 178
  • 212
6

If it's Oracle, use rownum.

SELECT SOMETABLE.*, ROWNUM RN
FROM SOMETABLE
WHERE SOMETABLE.SOMECOLUMN = :SOMEVALUE
ORDER BY SOMETABLE.SOMEOTHERCOLUMN;

The final answer will entirely depend on what database you're using.

FrustratedWithFormsDesigner
  • 26,726
  • 31
  • 139
  • 202
4

For MySql:

SELECT  @row := @row + 1 as row FROM anytable a, (SELECT @row := 0) r
BenV
  • 12,052
  • 13
  • 64
  • 92
2

use rownumber function available in sql server

SELECT 
    ROW_NUMBER() OVER (ORDER BY columnNAME) AS 'RowNumber',count(*) as usercount
    FROM users
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

How you'd do that depends on your database server. In SQL Server, you could use row_number():

select  row_number() over (order by age)
,       age
,       count(*) as usercount 
from    users 
group by 
        age
order by
        age

But it's often easier and faster to use client side row numbers.

Andomar
  • 232,371
  • 49
  • 380
  • 404
  • the `partition by age` will cause the number to rest for each `age`, and the query is grouping by age, so your row number will be 1 for every row. – KM. Jun 15 '10 at 18:12
0

for Mysql

set @row:=0;

select @row:=@row+1 as row, a.* from table_name as a;

srbcheema1
  • 544
  • 4
  • 16
0

In contrast to majority of other answers, and in accordance of the actual OP question, to

enumerate returned rows (...) NOT according to any column content

but rather in the order of returned query, one could use a dummy ordinal variable to ORDER BY in an ROW_NUMBER function, e.g.

ROW_NUMBER() OVER(ORDER BY (SELECT 0)) AS row_num

where one could actually use anything as an argument to the SELECT-statement, like SELECT 100, SELECT ‘A’, SELECT NULL, etc..

This way, the row numbers will be enumerated in the same order the data was added to the table.

Alaroff
  • 2,178
  • 1
  • 15
  • 9
  • 1
    Correct parantheses: `ROW_NUMBER() OVER(ORDER BY (SELECT 0)) AS row_num`. P.S. This answer does not work if ORDER BY is used in the query. – icemtel Dec 28 '20 at 20:05