0

I'm looking for a function to get result in below format:

Input:

| name     |
| -------- |
| DFHG     |
| DRTYFGJN |
| FGH      |
| FGH      |
| NBHFGD   |
| OIUKJH   |
| RTFHGJ   |
| TDHG     |

Desired output:

| id  | name     |
| --- | -------- |
| 1   | DFHG     |
| 2   | DRTYFGJN |
| 3   | FGH      |
| 4   | FGH      |
| 5   | NBHFGD   |
| 6   | OIUKJH   |
| 7   | RTFHGJ   |
| 8   | TDHG     |

Thank you in advance :)

zealous
  • 7,336
  • 4
  • 16
  • 36

1 Answers1

2

First option is by using variable

set @rank=0;

select
    @rank:=@rank+1 as id,
    name
from myTable
order by 
    name;

Second option is by using row_number(), only if you are using MySQL 8.0.

select 
    row_number() over (order by name) as id,
    name
from myTable;
zealous
  • 7,336
  • 4
  • 16
  • 36