104

For example I have a table with 2 columns, first_name and last_name with these values

Ali           Khani
Elizabette    Amini
Britney       Spears
,...

I want to write a select query that generate a table like this:

1     Ali           Khani
2     Elizabette    Amini
3     Britney       Spears
,...

Thanks for your help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
wf Khani
  • 1,055
  • 2
  • 7
  • 5

4 Answers4

181

If it is MySql you can try

SELECT @n := @n + 1 n,
       first_name, 
       last_name
  FROM table1, (SELECT @n := 0) m
 ORDER BY first_name, last_name

SQLFiddle

And for SQLServer

SELECT row_number() OVER (ORDER BY first_name, last_name) n,
       first_name, 
       last_name 
  FROM table1 

SQLFiddle

peterm
  • 91,357
  • 15
  • 148
  • 157
  • 1
    What if I want to seleect all columns from `table1` instead `first_name` and `last_name`, how can I refer to all? Trying `SELECT @n := @n + 1 n, *` doesn't work – PlainOldProgrammer May 14 '15 at 21:26
  • 1
    The answer is `SELECT @n := @n + 1 n, table1.*` – PlainOldProgrammer May 14 '15 at 21:38
  • 2
    In MYSQL you may need to initialize @n: `SET @n = 0;` – Francisco R Sep 29 '15 at 17:51
  • 2
    @FranciscoR Please take a closer look, it's already been initialized in the subquery `(SELECT @n := 0)`. The hidden beauty of this approach is that you have a single statement instead of two which is good when multiple statements are prohibited in your client code. – peterm Sep 29 '15 at 19:47
39

here's for SQL server, Oracle, PostgreSQL which support window functions.

SELECT  ROW_NUMBER() OVER (ORDER BY first_name, last_name)  Sequence_no,
        first_name,
        last_name
FROM    tableName
John Woo
  • 258,903
  • 69
  • 498
  • 492
6

In the case you have no natural partition value and just want an ordered number regardless of the partition you can just do a row_number over a constant, in the following example i've just used 'X'. Hope this helps someone

select 
    ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1, 
    period_next_id, period_name_long
from 
(
  select distinct col1, period_name_long, 'X' as num
  from {TABLE} 
) as x
Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169
balgar jagpal
  • 71
  • 1
  • 1
-1
DECLARE @id INT 
SET @id = 0 
UPDATE cartemp
SET @id = CarmasterID = @id + 1 
GO
josliber
  • 43,891
  • 12
  • 98
  • 133
Dev3
  • 25
  • 3