user2040500
user2040500

Reputation:

how to get the row sorted with title letter in mysql

i've a table

 ---------
|   NAME  |
|---------|
|  arun   |
|  balu   |
|  sunny  |
|  binu   |
|  binoy  |
|  cinny  |
|  aiju   |
|  dolly  |
 ---------   

i've wrote a query to get sorted list in mysql

SELECT name FROM students ORDER BY name ASC

and i got it all names sorted but i don't know how to get the output as shown below

 ---------
|   NAME  |
|---------|
|    A    |
|  aiju   |
|  arun   |
|    B    |
|  balu   |
|  binoy  |
|  binu   |
|    C    |
|  cinny  |
|    D    |
|  dolly  |
|    S    |
|  sunny  |
 ---------  

can anyone please tell me how to get this output?

Upvotes: 0

Views: 63

Answers (1)

Taryn
Taryn

Reputation: 247670

If you want to perform this in SQL, then you could use a UNION ALL query. The first query will return the name and the second query will return the first letter of each name. Then you can ORDER BY the result:

select name
from yourtable
union all
select distinct upper(left(name, 1))
from yourtable
order by name

See SQL Fiddle with Demo

The result is:

|  NAME |
---------
|     A |
|  aiju |
|  arun |
|     B |
|  balu |
| binoy |
|  binu |
|     C |
| cinny |
|     D |
| dolly |
|     S |
| sunny |

Upvotes: 2

Related Questions