How to get a numeric signature of a CHAR column in MySql - mysql

Given a CHAR or VARCHAR column in MySql, what I need is to convert it to a number so it can be summed up. For example, if the column name is CHAR1, the SELECT would be:
SELECT SUM(ConvertToNumber(CHAR1)) from TABLE1
The function ConvertToNumber just needs to convert to a number, it doesn't matter which number as long as it always converts to the same.
Is this feasible with native or user defined functions?
UPDATE: To be clear, the values of CHAR1 can be any string of alphanumeric characters.

What you can do is convert the column to the hexadecimal format, and then convert this result into base 10 to get an integer.
SELECT SUM(CONV(HEX(CHAR1), 16, 10)) FROM TABLE1;
For instance:
INSERT INTO TABLE1 (CHAR1) VALUES ("foo"), ("bar"), ("baz");
/* "int" value for each entry */
SELECT CONV(HEX(CHAR1), 16, 10) FROM TABLE1;
6713199
6447474
6447482
/* sum of the int values */
SELECT SUM(CONV(HEX(CHAR1), 16, 10)) FROM TABLE1
19608155

SELECT CAST(CHAR1 AS UNSIGNED) FROM TABLE1

Related

Can i use SUBSTR() inside of CAST() method?

I have a table called cities, with a column for timezones ( Timezone VARCHAR(10) NOT NULL that has timezones stored like: +00:00 or -02:00). - I am trying to select all cities that are two hours behind a city belonging to the +02:00 timezone.
I want to select the third character of the string and convert it to int. This is my approach:
SELECT CAST(SUBSTR(Timezone, 3, 1) AS INT)
FROM Cities;
My query returns error 1064. I cannot figure out why the syntax of my code is not correct. How can i solve this? Thank you!
SUBSTR(Timezone, 3, 1) returns the character that i want to modify. I do not want to replace it with 0, even if it would be easier, because having the posibility to do arithmetic operation with that number can help me reuse the code in future queries.
You need UNSIGNED (not INT) for CAST a numeric string as INTEGER
set #timezone ='+00:00';
SELECT CAST(SUBSTR(#Timezone, 3, 1) AS UNSIGNED)
and
SELECT CAST(SUBSTR(Timezone, 3, 1) AS UNSIGNED)
FROM cities

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);

Why is CAST function returning first value in comma-separated values, but not zero?

When I executed following query to find the country name by the ID, I accidentally passed a string that contained comma-separated values.
SELECT * FROM country WHERE id='6,AU,+61'
This query fetched that respective row.
When I tried casting this string into UNSIGNED using
SELECT CAST('6,AU,+61' AS UNSIGNED)
It returned 6, the first value.
When I tried integer values separated by comma (for eg: '7,8'), it also returned 7. So, it wasn't taking any values after the first comma.
In case of CAST('AU,+61' AS UNSIGNED), it returned zero.
Isn't '7,8' a string, so why is it not converting this into zero and taking first value instead?
MySql casts string to number by looking at the string from its left most char going right.
If the first char is a digit, it will iterate right until it reaches a non-digit char and will cast it to a number. if the string starts with a non-digit char it will cast to 0.
Thats why CAST('AU,+61' AS UNSIGNED) is 0
While CAST('7,8' AS UNSIGNED) is 7
However, The above is not documented specifically in the MySql Cast reference.
Although there are few examples over there and a specific line that implies such a behavior:
there are many different strings that may convert to the value 1, such as '1', ' 1', or '1a'.
However this can be validated with few simple tests:
SELECT CAST('a7' as UNSIGNED) as 'col_a7'; -- 0
SELECT CAST('7q6' as UNSIGNED) as 'col_7q6'; -- 7
SELECT CAST(' 7q6' as UNSIGNED) as 'col__7q6'; -- 7
SELECT CAST('1.4' as UNSIGNED) as 'col1.4'; -- 1
I might not be so clear in my description above, but these tests should clarify things.

Changing decimal places of a Double value MySQL

I have a database table called druginfo. It contains prices in WSprice column. Type of WSprice column is Double. This means It can contain like 23.5698 values. But I want to show all the values in the column WSprice 2 decimal places rounded like 23.57. How to apply that to all values in the column? Help me to do this.
If you only want to display your DOUBLE column to 2 decimal places, you can use the ROUND function:
SELECT ROUND(column_name, 2)
FROM your_table
This will display a value of 23.5698 as 23.57 in the result set.
If you want to change the format of the entire column you can use this:
ALTER TABLE your_table MODIFY column_name DECIMAL(9, 2)
I think we need to use CAST() instead of ROUND().
The reason behind is ROUND() return decimal values when decimal value exists in the database.
Example:
SELECT ROUND(columnName, 2)
FROM tableName
if columnName = 10.5 Output will be like 10.50
But if columnName = 10 Output will be like 10
And CAST() will return decimal value. But we need DECIMAL with CAST
SELECT CAST(columnName AS DECIMAL(10,2))
FROM tableName
The output will be like 10.00

Convert partially non-numeric text into number in MySQL query

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