Convert partially non-numeric text into number in MySQL query - mysql

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?

This should work:
SELECT field,CONVERT(SUBSTRING_INDEX(field,'-',-1),UNSIGNED INTEGER) AS num
FROM table
ORDER BY num;

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.

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]

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

SELECT *, CAST(SUBSTRING_INDEX(field, '-', -1) AS UNSIGNED) as num FROM tableName ORDER BY num;

one simple way SELECT '123'+ 0

cast(REGEXP_REPLACE(NameNumber, '[^0-9]', '') as UNSIGNED)

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

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

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;

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')),

A generic way to do :
SELECT * FROM your_table ORDER BY LENTH(your_column) ASC, your_column ASC

Related

Remove last digit from all data in column in MySQL

Just asking if this is possible:
I have a mysql database 'data' and a column 'count' which contains numbers such as
3741
49215
345
4686794
I was wondering if there is a possibility to remove the last figure from each number in this column, so there will be these values:
374
4921
34
468679
(for 100,000 rows so i can't do it manually :) )
Thank you!
This will work if the field is numeric or string and is always > 0:
UPDATE `table` SET `count` = FLOOR(`count`/10)
Note single digit values will become 0
If some numbers are negative, it will not give the right answer and a substring approach like the other answers is better.
Use the MySQL SUBSTRING function to extract portion of a string. Use CHAR_LENGTH function to calculate the number of characters in the string.
SELECT
col,
SUBSTRING(col, 1, CHAR_LENGTH(col) - 1) AS col_trimme
FROM tbl
is the data type is string you can
update my_table
set my_column = substr(my_column, 1, length(my_column) -2)
if is an int you can cast
update my_table
set my_column = cast(substr(cats(my_column AS varchar(16)), 1, length(my_column AS varchar(16)) -1), AS INT)
This will work if the field is numeric or string:
UPDATE table SET count = SUBSTRING(count, 1, CHAR_LENGTH(count) - 1);

not getting max value more than 999 in MySQL from varchar column

I have a VARCHAR column in MySQL table which stores only numbers. When I run querySELECT MAX(title_no) as title_no from mytable I get 999 but there are more records in table with value > 999 in title_no column.
I am not allowed to change the column from varchar to int. Please help me to get the correct nuber.
Thanks
MAX(CAST(title_no AS SIGNED))
.
You can use this one -
SELECT MAX(title_no * 1) AS title_no FROM mytable
You'll need to cast to a numeric type, otherwise it will be sorted as a string, not a number:
SELECT MAX(CAST(title_no AS SIGNED))
AS title_no
FROM mytable;
You need to use CAST here.Because it is treating as a string not as a number.Because you declared as varchar
MAX(CAST(title_no AS SIGNED))
It's because it will be character comparison as your field is of type varchar. You need to convert it to Integer. See this SQL FIDDLE
Try below another way.
SELECT MAX(CAST(title_no AS SIGNED)) AS title_no FROM mytable;
OR
SELECT MAX(CONVERT(title_no,UNSIGNED INTEGER)) FROM mytable;
OR
SELECT MAX(title_no * 1) AS title_no FROM mytable

MySQL sort varchar column numeric, numbers first

I've got a varchar column that I want to sort numeric, which works great when using this trick: https://stackoverflow.com/a/5418033/1005334 (in short: ...ORDER BY Result * 1).
However, the table concerned contains results. So something like this occurs:
Result
------
DNS
DNF
1
2
3
The numbers are correctly ordered, but the DNF comes above the numbers when sorting like this. What I'd like is to have the numeric sort, but with non-numbers sorted alphabetically below the numbers. Like so:
Result
------
1
2
3
DNF
DNS
In what way can I modify the query (preferably only the ORDER BY clause) to get this result?
use LPAD
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_lpad
LPAD(yourField, 20, '0');
this will manage correct order for "varchar numeric fields" (10 will be after 2) and put strings at the end.
SqlFiddle
The second argument (20) is quite arbitrary. It should be equivalent to (or bigger then) the length of the longest string in your field.
SELECT *, (Result REGEXP '^[0-9]+$') AS is_numeric
FROM table_name
ORDER BY is_numeric DESC,
CASE WHEN is_numeric THEN (Result + 0) ELSE Result END ASC
You can do that by using MySQL's REGEXP. Try this one,
SELECT *
FROM tablea
ORDER BY IF(`Result` REGEXP '^-?[0-9]+$', 0, 1) ASC,
`Result` ASC
SQLFiddle Demo
try this:
Please change your ORDER BY Clause with this:
ORDER BY
CASE WHEN Result REGEXP '^[0-9]+$' THEN Result*1 else 999999 END,
Result
This will order the numeric values first then the rest
ORDER BY CAST(`Result` AS SIGNED) DESC
this should work.

Mysql INT with a character

I have a mysql database with a field "order_number" set as an INT on the odd occasion the order number would need to have a trailing r eg 2100r obviously INT will only accept numbers and would sort the number correctly ASC or DESC if I use VARCHAR to overcome this restriction it will correctly accept the trailing r character but will not sort the numbers in numerical order correctly, is there a way INT option can be forced to accept a character?
You need to store your account ids as character strings if any of them contain letters. But you can order them correctly as long as the letters are always suffixes. This works whether or not your AccountID values have leading spaces.
SELECT *
FROM Account
ORDER BY CAST(AccountID as UNSIGNED INTEGER), AccountID
This will order numerically, and then deal with any equal numbers by ordering lexically.
http://sqlfiddle.com/#!2/a16bf/8/0
If you wanted the "r" orders to be shown before their unadorned friends with the same number, you could do this:
SELECT *
FROM Account
ORDER BY CAST(AccountID as UNSIGNED INTEGER), AccountID DESC
you can use CAST function in MySQL but it's a good practice to store order_number as int using typecasting before inserting new data in table.
SELECT CAST(int_col AS CHAR);
SELECT CAST(char_col AS unsigned INTEGER);
No, there is no such option.
You should probably use a VARCHAR column for the order number and a separate column (possibly INT) just for sorting; populate the helper column based on what the order number is when inserting and updating rows.
Try to convert string to number using this way (number_string * 1), e.g. -
SELECT * FROM table ORDER BY column * 1;
No , Not possible. As #Jon said, there is no other options to force an INT field to keep VARCHAR data.

mysql sort string number

I have a column of type varchar that stores many different numbers. Say for example there are 3 rows: 17.95, 199.95 and 139.95.How can i sort that field as numbers in mysql
Quickest, simplest? use * 1
select *
from tbl
order by number_as_char * 1
The other reasons for using * 1 are that it can
survive some horrendous mishaps with underflow (reduced decimal precision when choosing what to cast to)
works (and ignores) columns of purely non-numeric data
strips numeric portions of alphanumeric data, such as 123A, 124A, 125A
If you need to sort a char column containing text AND numbers then you can do this.
tbl contains: 2,10,a,c,d,b,4,3
select * from tbl order by number_as_char * 1 asc, number_as_char asc
expected output: 2,3,4,10,a,b,c,d
If you don't add the second order by argument only numbers will be sorted - text actually gets ignored.
Use a CAST or a CONVERT function.
This approach is helpful when sorting text as numbers:
SELECT `my_field`
FROM `my_table`
ORDER BY `my_field` + 0;
Found the solution on http://crodrigues.com/trick-mysql-order-string-as-number/.
Pad the string with leading zeroes:
ORDER BY LPAD(`column`,<max length of string>,"0")
If you really have to you can do this if your source data is compatible:
SELECT column FROM table ORDER BY CAST(column AS DECIMAL(10,2))
It's not going to be very fast for large data sets though. If you can you should change the schema to use DECIMAL in the first place though. Then it can be properly indexed for better performance.