How to get the datatype of MySQL table columns?

MySQLMySQLi Database

You can get the MySQL table columns data type with the help of “information_schema.columns”.

The syntax is as follows −

SELECT DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where
table_schema = ’yourDatabaseName’ and table_name = ’yourTableName’.

To understand the above syntax, let us first create a table −

mysql> create table DataTypeDemo
−> (
   −> Id int,
   −> Address varchar(200),
   −> Money decimal(10,4)
−> );
Query OK, 0 rows affected (0.60 sec)

Apply the above syntax to get the MySQL columns data type. The query is as follows −

mysql> select data_type from information_schema.columns where table_schema = 'business' and able_name = 'DataTypeDemo';

The following is the output −

+-----------+
| DATA_TYPE |
+-----------+
| int       |
| varchar   |
| decimal   |
+-----------+
3 rows in set (0.00 sec)

If you want, include the column name as well in the output before the datatype. The query is as follows −

mysql> select column_name,data_type from information_schema.columns where table_schema = 'business' and table_name = 'DataTypeDemo';

The following output displays the column name corresponding to the data type −

+-------------+-----------+
| COLUMN_NAME | DATA_TYPE |
+-------------+-----------+
| Id          | int       |
| Address     | varchar   |
| Money       | decimal   |
+-------------+-----------+
3 rows in set (0.00 sec)
raja
Published on 10-Jan-2019 05:57:11
Advertisements