Click here to Skip to main content
15,884,177 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using order by in select query
like
SQL
select emp_id,emp_nm from emp order by emp_id asc


but the problem is :produced result by query is:
emp_id | emp_nm
E1 | A
E10 | B
E11 | C
E2 | D
E3 | E
E4 | F

But, i want like this:
emp_id | emp_nm
E1 | A
E2 | B
E3 | C
E10 | D
E11 | E

Is it possible in sql?

What I have tried:

I am using order by in select query
like
select emp_id,emp_nm from emp order by emp_id asc
Posted
Updated 27-Dec-17 22:55pm
v2

1 solution

That's because you are ordering by a string quantity, and string order is defined by the first different character between two strings. In your case, E2 comes after E1, E10, and E11 because the first different character is '2' in one string and '1' in the other: because '1' comes before '2' in the character set, all strings starting "E1" will come before all strings starting "E2" - the remaining characters are not considered at all.

You can't get round that, or not easily, because that is how strings work!
There are three things you can do:
1) Pad your ID's with leading zeros:
E01 | A
E10 | B
E11 | C
E02 | D
E03 | E
E04 | F 

2) Use a computed column to give you a character prefix and an integer count: Generated Columns in MySQL 5.7.5 | MySQL Server Blog[^]
3) Write a function to split your ID, convert the numeric part to a number, and use that for ordering.
Me? I don't use "mixed" id's for this very reason!
 
Share this answer
 
Comments
CodeEager 28-Dec-17 5:08am    
Ok sir,I understood

I will choose first because it will be easy for me.
Thank You.
OriginalGriff 28-Dec-17 5:13am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900