473,379 Members | 1,252 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

mySQL natural sort

Hi everyone.
I have two tables in the same DB. They both contain alphanumeric codes like "XX123". (one looks up the other) I need to do a natural sort on these in both tables. In one table if I use the trick +0 it works perfectly :

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM  `thistable` ORDER BY  `thiscode` + 0 ASC
However in the other table
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM `product_master_file` ORDER BY `thiscode`+ 0 ASC  
produces no obvious sort at all. However I know the syntax is ok as leaving out the +0 gives the expected result (which is not a natural search)

I can only think there is some difference in the tables? The field in question is a varchar 15 characters in both and the second one has been populated by the first. The only difference I can see is in the one that works NULL=No Default = blank and in the non working one NULL=Yes and Default=Null but I cant see why this would affect it

I don't have much hair but this is causing the remaining to fall out!
your help most appreciated
Feb 17 '10 #1

✓ answered by Atli

MySQL has no built in support for this sort of natural sorting. It sorts strings in a very linear way; one char at a time starting at index 0. - The is the main reason why it is recommended that you don't store codes in such a way, but rather separated into their individual parts.

However, if your code is in a fairly standard format, you can "simulate" natural sorting (up to a point). - For example, if your code always starts with two letters, followed by a number, followed by a mix of alpha-numeric characters, you can sort the strings by the letters and numbers like so:
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM `tbl`
  2. ORDER BY
  3.     LEFT(`code`, 2),
  4.     CAST(SUBSTR(`code`, 3) AS SIGNED);
This is of course very limited. Anything after (and including) the first alpha character after the first numeric character would be ignored.

You may be better of doing this sort of sorting on the front-end or by creating a MySQL function.

The ideal solution would of course be to find a way to separate the values the code is made out of and store them in individual columns. That would effectively eliminate this problem.

4 23222
Atli
5,058 Expert 4TB
Hey.

When you say: "XX123", are the X characters actual "X" string characters, or do they represent something else?
If they are just strings, then doing +0 would (should) not yield any usable results, as it would always return 0. (Doing arithmetic calculations on a string, who's first char is not a number, will always return 0.)

Try looking at the actual value it is being sorted on. You should be able to just add it to the SELECT, like:
Expand|Select|Wrap|Line Numbers
  1. SELECT *, `thiscode` + 0 AS 'sort_order' ...
Feb 18 '10 #2
Thanks so much for your insight. Perhaps I can approach solving my problem by asking my question in a differnt way. The field is a VARCHAR. Examples of values are SG1, SGO1, SG147a, SG12 (ie all start with an alpha, but then a mix of alpha/number.

How would you do a natural sort on this? Would, for example ORDER BY CASE('thisfield' AS SIGNED) be the correct approach. Many thanks
Feb 18 '10 #3
Atli
5,058 Expert 4TB
MySQL has no built in support for this sort of natural sorting. It sorts strings in a very linear way; one char at a time starting at index 0. - The is the main reason why it is recommended that you don't store codes in such a way, but rather separated into their individual parts.

However, if your code is in a fairly standard format, you can "simulate" natural sorting (up to a point). - For example, if your code always starts with two letters, followed by a number, followed by a mix of alpha-numeric characters, you can sort the strings by the letters and numbers like so:
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM `tbl`
  2. ORDER BY
  3.     LEFT(`code`, 2),
  4.     CAST(SUBSTR(`code`, 3) AS SIGNED);
This is of course very limited. Anything after (and including) the first alpha character after the first numeric character would be ignored.

You may be better of doing this sort of sorting on the front-end or by creating a MySQL function.

The ideal solution would of course be to find a way to separate the values the code is made out of and store them in individual columns. That would effectively eliminate this problem.
Feb 18 '10 #4
Thank you very much for your time and trouble. You answered my question clearly and concisely and were most helpful, I really appreciate it. Regards
Feb 18 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Bob | last post by:
I am sure this has been answered in over whelming detail in this group, however the search results have not turned up any thing I am interested in. I want a simple form generator in PHP that...
0
by: C. Barnes | last post by:
Summary: Sorts strings in a way that seems natural to humans. If the strings contain integers, then the integers are ordered numerically. For example, sorts into the order . Code:
1
by: Connelly Barnes | last post by:
Summary: Sorts strings in a way that seems natural to humans. If the strings contain integers, then the integers are ordered numerically. For example, sorts into the order . Code: ...
1
by: jlee | last post by:
I'm pretty much a newbie on mysql, and I need some help. I am running mysql Ver 12.22 Distrib 4.0.24, for portbld-freebsd5.4 (i386) on a server hosting an active website. The site's developer...
39
by: windandwaves | last post by:
Hi Folk I have to store up to eight boolean bits of information about an item in my database. e.g. with restaurant drive-through facility yellow windows
1
by: Ike | last post by:
Recently, I began using a different MySQL verver (i.e. different machine as well as different version#, going from 4.12a to 4.1.9 max). The following query used to work: select firstname,...
8
by: The Natural Philosopher | last post by:
This is so weird. What I am trying to do is to upload files and stuff them in a mysql database. Everything works except the file content is zero. using the load_file command from mysql...
5
by: martin99 | last post by:
Hi, I can run a test scrip that connects to the and it CONNECTS successfully whilst running from the my website on the server. $sqlhost = 'localhost'; $sqluser = 'userid'; $sqlpass =...
30
by: Einstein30000 | last post by:
Hi, in one of my php-scripts is the following query (with an already open db-connection): $q = "INSERT INTO main (name, img, descr, from, size, format, cat, host, link, date) VALUES ('$name',...
15
by: Franz Marksteiner | last post by:
Hi folks, I am looking for the straightest way to export a whole MySql database, but all I can find is SQL statements to export specific tables. Any suggestions? -- Freundliche Grüße, Franz...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.