Convert partially non-numeric text into number in MySQL query
Asked Answered
B

12

159

Is it possible to convert text into a number within MySQL query? I have a column with an identifier that consists a name and a number in the format of "name-number". The column has VARCHAR type. I want to sort the rows according to the number (rows with the same name) but the column is sorted according to do character order, i.e.

name-1
name-11
name-12
name-2

If I cut off the number, can I convert the 'varchar' number into the 'real' number and use it to sort the rows? I would like to obtain the following order.

name-1
name-2
name-11
name-12

I cannot represent the number as a separate column.

edited 2011-05-11 9:32

I have found the following solution ... ORDER BY column * 1. If the name will not contain any numbers is it safe to use that solution?

Bathilda answered 11/5, 2011 at 7:18 Comment(3)
name is exactly name or it can be any character? I mean: is it a string four chars long or is a real name?Squama
name can be any sequence of letters.Bathilda
possible duplicate of mysql natural sortingKinakinabalu
S
286

This should work:

SELECT field,CONVERT(SUBSTRING_INDEX(field,'-',-1),UNSIGNED INTEGER) AS num
FROM table
ORDER BY num;
Squama answered 11/5, 2011 at 7:28 Comment(6)
could you add an explanation and a link to the documentation?Australoid
My string is like "name-abc12". By adding your code, it only works if the initial characters after "-" not starts with a letter. @Squama Can you tell me a way to ignore the letters without a where condition?Marthena
@Marthena my query is supposed to get the string after the "-" and convert it into a number (it MUST be a number). In your case I'd go on using a regular expression probably...Squama
@Squama regular expression did it, thank you for the tip.Marthena
More info on this commandBhutan
@Marthena Marco is using SUBSTRING_INDEX which uses a given separator (- in this case) to split the string in "columns" and return the portion of that separation that you ask for (with the third argument). All details in the documentation: dev.mysql.com/doc/refman/5.7/en/…Kayceekaye
D
37

You can use SUBSTRING and CONVERT:

SELECT stuff
FROM table
WHERE conditions
ORDER BY CONVERT(SUBSTRING(name_column, 6), SIGNED INTEGER);

Where name_column is the column with the "name-" values. The SUBSTRING removes everything up before the sixth character (i.e. the "name-" prefix) and then the CONVERT converts the left over to a real integer.

UPDATE: Given the changing circumstances in the comments (i.e. the prefix can be anything), you'll have to throw a LOCATE in the mix:

ORDER BY CONVERT(SUBSTRING(name_column, LOCATE('-', name_column) + 1), SIGNED INTEGER);

This of course assumes that the non-numeric prefix doesn't have any hyphens in it but the relevant comment says that:

name can be any sequence of letters

so that should be a safe assumption.

Diaper answered 11/5, 2011 at 7:27 Comment(2)
Answering my comment, he told us name can be any sequence of chars, so I'm not sure you can use SUBSTRING(name_column, 6). I know, you posted it when he didn't tell us this...Squama
@Marco: Thanks for the heads up, I added an update that should take care of the new information about the prefixes. But yeah, your SUBSTRING_INDEX is nicer.Diaper
H
29

Simply use CAST,

CAST(column_name AS UNSIGNED)

The type for the cast result can be one of the following values:

BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Hoopoe answered 16/11, 2016 at 5:23 Comment(0)
P
17

You can use CAST() to convert from string to int. e.g. SELECT CAST('123' AS INTEGER);

Propylene answered 11/5, 2011 at 7:25 Comment(1)
Is that version specific? I need to use SELECT CAST('123' AS SIGNED INTEGER); or SELECT CAST('123' AS UNSIGNED INTEGER); to get it to work.Festival
K
10
SELECT *, CAST(SUBSTRING_INDEX(field, '-', -1) AS UNSIGNED) as num FROM tableName ORDER BY num;
Krispin answered 11/5, 2011 at 7:29 Comment(1)
Are you sure that the ORDER BY uses num as a number without using CONVERT? I'm not sure, but it can be.. I'm just asking myself :)Squama
A
9

one simple way SELECT '123'+ 0

Apicella answered 4/7, 2016 at 6:45 Comment(3)
Although this code may be help to solve the problem, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.Alcantar
This did not answer the question but it was the answer i was looking for.Nigel
your solution is the most elegant and practical - unfortunately you didnt provide it in the context of the question with specific expression for given example - please modify it to be specific.Chiffonier
C
5
cast(REGEXP_REPLACE(NameNumber, '[^0-9]', '') as UNSIGNED)
Current answered 11/1, 2020 at 10:43 Comment(2)
Exactly what I want :)Judyjudye
It's my fortune, I came out helpful for you.Current
G
3

To get number try with SUBSTRING_INDEX(field, '-', 1) then convert.

Granadilla answered 11/5, 2011 at 7:26 Comment(1)
You need to change 1 to -1. dev.mysql.com/doc/refman/5.0/en/…Krispin
E
2

if your primary key is a string in a format like

ABC/EFG/EE/13/123(sequence number)
this sort of string can be easily used for sorting with the delimiter("/")

we can use the following query to order a table with this type of key

SELECT * FROM `TABLE_NAME` ORDER BY 
CONVERT(REVERSE(SUBSTRING(REVERSE(`key_column_name`), 1, LOCATE('/', REVERSE(`key_column_name`)) - 1)) , UNSIGNED INTEGER) DESC
Erastian answered 15/7, 2013 at 11:25 Comment(0)
T
0

I found it easier to use regex_replace function to strip off all non numeric values from the field and then sort.

SELECT field , CONVERT(REGEXP_REPLACE(field,'[^0-9]',''),UNSIGNED) AS num FROM your_table ORDER BY num;
Tranche answered 9/7, 2021 at 14:23 Comment(0)
T
-2
select
    `a`.uuid,
    concat('1',REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(`a`.uuid,'-',''),'b','11'),'c','12'),'d','13'),'e','14'),'f','15'),'a','10')),
Trill answered 9/3, 2021 at 3:19 Comment(2)
Please add some explanation to your answer such that others can learn from itAlike
This one may just be responding to the title of this post - converting text to number (in this case a text uuid string) -- using replace (or pretty much anything else) is generally faster than a regex. This also suggests the idea of using a uuid string as primary key. A plain old autoincrement or perhaps a binary uuid would be faster than conversion to string if that is the goal in this case.Disconnected
M
-5

A generic way to do :

SELECT * FROM your_table ORDER BY LENTH(your_column) ASC, your_column ASC
Microcurie answered 13/4, 2017 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.