MySQL query to convert height format to centimeters?

MySQLi Database

For this, use the CAST() method in MySQL. Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentHeight varchar(40)
) ;
Query OK, 0 rows affected (0.47 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentHeight) values('5\'10\"');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentHeight) values('4\'6\"');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentHeight) values('5\'8\"');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+---------------+
| Id | StudentHeight |
+----+---------------+
|  1 | 5'10"         |
|  2 | 4'6"          |
|  3 | 5'8"          |
+----+---------------+
3 rows in set (0.00 sec)

Following is the query to convert height format to centimeters −

mysql> select
   (cast(substr(StudentHeight,1,locate("'",StudentHeight)-1) as unsigned)*30.48)+
   (cast(substr(StudentHeight,locate("'",StudentHeight)+1) as unsigned)*2.54) AS Centimeters
   from DemoTable;

This will produce the following output −

+-------------+
| Centimeters |
+-------------+
| 177.80      |
| 137.16      |
| 172.72      |
+-------------+
3 rows in set, 3 warnings (0.05 sec)
raja
Published on 04-Oct-2019 08:11:35
Advertisements