Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Order by Second Letter of Column Name

Tags:

sql

sql-server

I have a column of lets say 10 values all NCHAR(20) in SQL Server.

I want to sort the Values by the 2nd Letter in a Descending manner. In other Words if i have the following column values. Note this should work with any values this is just examples.

  • Earth
  • Space
  • Moon
  • Star
  • Pluto

The SQL Query must produce the Following Output

  • Star
  • Space
  • Moon
  • Pluto
  • Earth

The closest I could come to an answer was This -

Select planet, name from galaxy WHERE planet like '_%' ORDER BY planet desc

like image 596
Desmond Smith Avatar asked Nov 21 '25 18:11

Desmond Smith


2 Answers

ORDER BY SUBSTRING(planet , 2, 1) DESC

It`s good to check the docs from time to time Link

like image 79
Mihai Avatar answered Nov 24 '25 06:11

Mihai


You can ORDER BY SUBSTR(planet, 2) DESC

This means minus the first character.

like image 28
malta Avatar answered Nov 24 '25 07:11

malta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!