Is it okay to store double and date in VARCHAR with MySQL?


Yes, you can store double and date in VARCHAR. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Amount varchar(20),
   -> JoiningDate varchar(20)
   -> );
Query OK, 0 rows affected (0.96 sec)

Insert some records in the table using insert command. We are inserting varchar double and date values −

mysql> insert into DemoTable values('150.50','Oct 10,2019');
Query OK, 1 row affected (0.91 sec)
mysql> insert into DemoTable values('173.45','Sept 11,2018');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('173.90','Jan 01,2017');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+--------+--------------+
| Amount | JoiningDate  |
+--------+--------------+
| 150.50 | Oct 10,2019  |
| 173.45 | Sept 11,2018 |
| 173.90 | Jan 01,2017  |
+--------+--------------+
3 rows in set (0.00 sec)

Now, we are storing the VARCHAR records to DOUBLE and DATE types −

mysql> select Amount+0.0 as DoubleValue,str_to_date(JoiningDate,'%M %d,%Y') as Date from DemoTable;

This will produce the following output −

+-------------+------------+
| DoubleValue | Date       |
+-------------+------------+
|       150.5 | 2019-10-10 |
|      173.45 | 2018-09-11 |
|       173.9 | 2017-01-01 |
+-------------+------------+
3 rows in set (0.04 sec)

Updated on: 26-Feb-2020

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements