How to convert Varchar to Double in SQL?


You can convert varchar to double using CAST() function. The syntax is as follows:

SELECT yourColumnName1,yourColumnName2,......N, CAST(yourColumnName AS DECIMAL(TotalDigit,DigitAfterDecimalPoint)) anyVariableName FROM yourtableName
ORDER BY anyVariableName DESC;

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table VarcharToDouble
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(10),
   -> Amount varchar(10) ,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command. The query is as follows:

mysql> insert into VarcharToDouble(Name,Amount) values('John','456.78');
Query OK, 1 row affected (0.14 sec)
mysql> insert into VarcharToDouble(Name,Amount) values('Larry','8465.98');
Query OK, 1 row affected (0.18 sec)
mysql> insert into VarcharToDouble(Name,Amount) values('Mike','9083.45');
Query OK, 1 row affected (0.12 sec)
mysql> insert into VarcharToDouble(Name,Amount) values('Sam','46475.50');
Query OK, 1 row affected (0.19 sec)
mysql> insert into VarcharToDouble(Name,Amount) values('Carol','10003.35');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement. The query is as follows:

mysql> select *from VarcharToDouble;

The following is the output:

+----+-------+----------+
| Id | Name  | Amount   |
+----+-------+----------+
|  1 | John  | 456.78   |
|  2 | Larry | 8465.98  |
|  3 | Mike  | 9083.45  |
|  4 | Sam   | 46475.50 |
|  5 | Carol | 10003.35 |
+----+-------+----------+
5 rows in set (0.00 sec)

Here is the query to convert varchar to double using CAST():

mysql> select Id,Name, CAST(Amount AS DECIMAL(10,2)) TotalAmount from VarcharToDouble
   -> order by TotalAmount desc;

The following is the output:

mysql> select Id,Name, CAST(Amount AS DECIMAL(10,2)) TotalAmount from VarcharToDouble
   -> order by TotalAmount desc;

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements