Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@MichelPoulain
Created July 20, 2010 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichelPoulain/483594 to your computer and use it in GitHub Desktop.
Save MichelPoulain/483594 to your computer and use it in GitHub Desktop.
/*
NATURAL ORDER in MySQL !
*/
-- Create test table
--
DROP TABLE IF EXISTS `natural_sort`;
CREATE TABLE IF NOT EXISTS `natural_sort` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
`val` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- Fill in table with example values
--
INSERT INTO `natural_sort` (`id`, `val`) VALUES
(1, '1100W'),
(2, 'c'),
(3, '1400W'),
(4, '750W'),
(5, 'a'),
(6, '500W'),
(7, 'b');
-- Natural sort function (as on Macintosh)
--
-- first order: deal with every values as numbers
-- second order: order every row not ordered because equals (=letters)
SELECT *
FROM `natural_sort`
ORDER BY
`natural_sort`.`val` +0 ,
`natural_sort`.`val`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment