Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting VARCHAR to DECIMAL values in MySql

I have imported a CSV file that contains string values (eg.eating) and floating values (eg. 0.87) into a table in my phpMyAdmin database. After I get ride of all the string values and retain only the rows that have the decimal values, I need to convert such values from VARCHAR to DECIMAL/FLOAT so that I can perform a MAX() on this attribute.

How do I do this? Each time I try doing this through the GUI in phpMyAdmin, all my values are automatically rounded off to 0 and 1s.

Please help me!

like image 618
Darth Coder Avatar asked Mar 09 '14 05:03

Darth Coder


People also ask

How do I convert varchar to numeric in SQL?

To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.

Can varchar store DECIMAL?

The short answer is: No, it will hurt performance. The longer answer: VARCHAR fields are variable length, meaning, that the formatting of the database blocks cannot pre-account for the size of the data filling in there.

How do I convert a number to a DECIMAL in SQL?

Use the CAST() function to convert an integer to a DECIMAL data type. This function takes an expression or a column name as the argument, followed by the keyword AS and the new data type. In our example, we converted an integer (12) to a decimal value (12.00).


3 Answers

Without Converting you can find Maximum using this query

select max(cast(stuff as decimal(5,2))) as mySum from test;

check this SQLfiddle

your demo table:

create table test (
   name varchar(15),
   stuff varchar(10)
);

insert into test (name, stuff) values ('one','32.43');
insert into test (name, stuff) values ('two','43.33');
insert into test (name, stuff) values ('three','23.22');

Your Query:

For SQL Server, you can use:

select max(cast(stuff as decimal(5,2))) as mySum from test;
like image 94
Jaykumar Patel Avatar answered Oct 07 '22 00:10

Jaykumar Patel


Be aware that if you convert from VARCHAR to DECIMAL and do not specify a precicision and maximum number of digits (i.e. DECIMAL instead of DECIMAL(5,2)) MySQL will automatically round your decimals to integer values.

like image 25
Alex W Avatar answered Oct 06 '22 23:10

Alex W


I think you need to try doing something like this on your MySQL if you have admin privilege on your MySQL.

ALTER TABLE tablename MODIFY columnname DECIMAL(M,D)

for the M,D variables, read this - http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html

And MySQL should be able to automatically converting a text to a numeric. Just that the data type in MySQL might not be a decimal yet that's why you can't store any decimal.

like image 38
Sky Avatar answered Oct 07 '22 00:10

Sky