0

I have the following data:

GROUP 1 - FINANCE
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR
GROUP 2 - OPS

When ORDERING the data in a MySQL question it, rightly, brings this data back in the above order. However, is there anyway (without changing the data you can order it in Numeric order? As follows

GROUP 1 - FINANCE
GROUP 2 - OPS
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR

Thanks!

3
  • Is that column was numerical in the database it would do it automatically. Can you change the schema? Otherwise a simple cast to int before ordering would work. p.s I'm pretty sure this question has been answered many times on here already and a simple google would also sort it. Commented Jun 25, 2018 at 14:39
  • Here is an article that might be helpful. copterlabs.com/natural-sorting-in-mysql as @webnoob mentioned, you would be better off changing the schema, but if that's not possible, you would have a much easier time implementing a sort in php IMO (which is perfectly acceptable if the data set is small). Commented Jun 25, 2018 at 14:45
  • have you got any column which show it number? because if you want to sort by numbers you need numeric column. Commented Jun 25, 2018 at 14:45

2 Answers 2

1

Adding ORDER BY CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(column, ' ', 2), ' ', -1) AS UNSIGNED) clause should help.

Nesting SUBSTRING_INDEX functions with the right parameters makes it possible to split and extract the string parts. it this case the numeric part after the first string part in this case 'GROUP' will be extracted.

Query

SELECT
 records.data
FROM (

SELECT 
 "GROUP 1 - FINANCE" AS data
UNION 
SELECT 
 "GROUP 10 - SALES" AS data
UNION 
SELECT 
 "GROUP 11 - MARKETING" AS data 
UNION 
SELECT 
 "GROUP 12 - HR" AS data  
UNION 
SELECT 
 "GROUP 2 - OPS" AS data   
) AS records
ORDER BY 
 CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(records.data, ' ', 2), ' ', -1) AS UNSIGNED)

see demo https://www.db-fiddle.com/f/sGqUeTKaDjihRA3Bg3Myca/0

Sign up to request clarification or add additional context in comments.

Comments

0

Since MySQL 8.0 you can use REPLACE and REGEXP_SUBSTR to ORDER BY the column:

SELECT * 
FROM table_name
ORDER BY CAST(TRIM(REPLACE(REGEXP_SUBSTR(column_name, '(GROUP )([0-9]+)'), 'GROUP', '')) AS UNSIGNED)

1 Comment

MySQL doesn't understand INT as a CAST type (you get a parse error) you need to use UNSIGNED instead. see demo db-fiddle.com/f/jkzdNKhdeTJbsko4GbkNAg/0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.