Anshika Jain
Anshika Jain

Reputation: 177

How can I use Order By with MySQL in this case?

Select name, LENGTH(name) 
  from Employees 
  order by LENGTH(name);

Why doesn't this give me sorted Lengths? It is still sorting based on name.

Input Employees :

Emp | Salary
------------
DEF |  30
PQRS|  40
ABC |  30
WXY |  20

Expected:

ABC  3
DEF  3
WXY  3
PQRS 4

Upvotes: 0

Views: 34

Answers (2)

James Brown
James Brown

Reputation: 37404

Tested:

SELECT name, LENGTH(name) 
FROM Employees 
ORDER BY 2;

Then again your query seems to work as well.

Upvotes: 2

jmarkmurphy
jmarkmurphy

Reputation: 11473

Your expected output shows the data sorted by length then name, but your SQL will not guarantee that.

Select name, LENGTH(name) 
  from Employees 
  order by LENGTH(name), name;

The above modification will sort first by length, then by name, and you will get the expected output for your input.

Upvotes: 1

Related Questions