Jump to content

varchar order by problem


ted_chou12

Recommended Posts

Hi I have a column that is in varchar and I tried to order by asc, and it looks like this

L1

L10

L11

L12

L2

L3

L4

L5

L6

L7

...

instead i want it to be numerical logically ordered... eg

L1

L2

L3

L4

...

L10

L11

is there a special function that is needed to be added in the order by query for it to be ordered properly?

Thanks,

Ted

Link to comment
Share on other sites

Hi, thanks,

that kind of worked a bit, but the result came out like this:

1

2

3

4

5

6

7

8

9

10

L1

D1

11

S1

L2

12

S2

L3

13

S3

L4

S4

L5

S5

L6

S6

L7

S7

L8

S8

S9

I guess the numbered are ordered, but the letters are ordered differently  :-\, i found out that this is a well known bug in mysql.

Thanks for your help though  :P

Link to comment
Share on other sites

It's not a bug, it's you expecting strings to act like numbers. You also did not bother to mention in the first post that there were numbers and letter-numbers involved.

 

When there is a leading letter, will there always be only one?

 

The most direct solution is for you to make all the number fields the same format/length. Instead of L1, use L01 (assuming a maximum number of 99 will be used.)

Link to comment
Share on other sites

The link you posted to the webdev... thread is equally wrong. Strings are sorted character, by character, left to right. It has nothing to do with the length and it is not a bug. The suggestion to add 0 to a string that contains a number will cause that string to be converted to a number and would work except your issue is different because you also have letter-numbers.

Link to comment
Share on other sites

hi, thanks for all the suggestions,

LEFT(id, 1),  (SUBSTR(id, ((id REGEXP '[^a-z]') + 1)) + 0)

ive got the second part, which basically means if the id has not letters in it, read from first character, if it does, read from second which outputs:

L1

S1

1

L2

S2

2

...

L10

S10

10

...

but the first part is not putting it correctly, is it possible to use regex to determine if the string has no letters in it, then add a 0 in the front so it becomes 01, 02, 03...?

Thanks,

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.