143

I want to get the column data type of a mysql table.

Thought I could use MYSQLFIELD structure but it was enumerated field types.

Then I tried with mysql_real_query()

The error which i am getting is query was empty

How do I get the column data type?

0

12 Answers 12

153

You can use the information_schema columns table:

SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE table_name = 'tbl_name' AND COLUMN_NAME = 'col_name';
8
  • 10
    Don't forget: AND INDEX_SCHEMA = 'database_name'
    – Inshallah
    Aug 6, 2009 at 18:16
  • I personally tried this and would agree this answer does do what the OP intended to. On a side note a bit weird on how "table_name" is small caps even in the manual, should it not be UPPER? (Not that it makes a difference)
    – chutsu
    Jun 13, 2012 at 12:59
  • 10
    Also note if the data type has a set length, eg. VARCHAR(50) one can use SELECT COLUMN_TYPE to get that extra information.
    – chutsu
    Jun 13, 2012 at 13:02
  • 12
    if INDEX_SCHEMA doesn't work then try TABLE_SCHEMA = 'database_name'
    – senK
    Apr 11, 2013 at 4:15
  • 2
    This query is useless when you want to know the type for all columns (removing AND COLUMN_NAME = 'col_name') unless you display the column name : SELECT COLUMN_NAME, DATA_TYPE FROM etc.. Aug 5, 2015 at 10:34
113

The query below returns a list of information about each field, including the MySQL field type. Here is an example:

SHOW FIELDS FROM tablename
/* returns "Field", "Type", "Null", "Key", "Default", "Extras" */

See this manual page.

3
  • 26
    An alternative is EXPLAIN tablename;
    – hobodave
    Jul 31, 2009 at 23:58
  • 1
    This answer requires further handling to get the type... The answer user83591 gave is much better
    – chutsu
    Jun 13, 2012 at 12:59
  • Add WHERE FIELD = '<your column name>' if you want a single column info.
    – Placid
    Apr 2, 2020 at 22:33
64

Most answers are duplicates, it might be useful to group them. Basically two simple options have been proposed.

First option

The first option has 4 different aliases, some of which are quite short :

EXPLAIN db_name.table_name;
DESCRIBE db_name.table_name;
SHOW FIELDS FROM db_name.table_name;
SHOW COLUMNS FROM db_name.table_name;

NB: In each case, you can also write FROM two times instead of db_name.table_name, example:

SHOW FIELDS FROM table_name FROM db_name

This gives something like :

+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| product_id       | int(11)      | NO   | PRI | NULL    |       |
| name             | varchar(255) | NO   | MUL | NULL    |       |
| description      | text         | NO   |     | NULL    |       |
| meta_title       | varchar(255) | NO   |     | NULL    |       |
+------------------+--------------+------+-----+---------+-------+

Second option

The second option is a bit longer :

SELECT
  COLUMN_NAME, DATA_TYPE 
FROM
  INFORMATION_SCHEMA.COLUMNS 
WHERE
  TABLE_SCHEMA = 'db_name'
AND
  TABLE_NAME = 'table_name';

It is also less talkative :

+------------------+-----------+
| column_name      | DATA_TYPE |
+------------------+-----------+
| product_id       | int       |
| name             | varchar   |
| description      | text      |
| meta_title       | varchar   |
+------------------+-----------+

It has the advantage of allowing selection per column, though, using AND COLUMN_NAME = 'column_name' (or like).

1
  • This second option was exactly what I needed. Thanks so much for this!
    – Blake Neal
    Jan 11 at 16:40
29

To get data types of all columns:

describe table_name

or just a single column:

describe table_name column_name
1
  • Didn't know you could do this. You just saved me a bunch of tramping through the information schema.
    – Betty Mock
    May 5, 2020 at 21:35
20

Please use the below mysql query.

SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH 
FROM information_schema.columns 
WHERE table_schema = '<DATABASE NAME>' 
AND table_name = '<TABLE NAME>' 
AND COLUMN_NAME = '<COLOMN NAME>' 

MySql Query Result

2
  • But this will give only the maximum length. Isn't it better to use SELECT DATA_TYPE, as proposed by other answers? Jun 29, 2017 at 11:30
  • Yes, You are right. I just forgot to add it. I am now corrected it. Thanks Jun 29, 2017 at 16:13
8

First select the Database using use testDB; then execute

desc `testDB`.`images`;
-- or
SHOW FIELDS FROM images;

Output:

Get Table Columns with DataTypes

5

Refer this link

mysql> SHOW COLUMNS FROM mytable FROM mydb;
mysql> SHOW COLUMNS FROM mydb.mytable;

Hope this may help you

2

Query to find out all the datatype of columns being used in any database

SELECT distinct DATA_TYPE FROM INFORMATION_SCHEMA.columns 
WHERE table_schema = '<db_name>' AND column_name like '%';
1
1

SHOW COLUMNS FROM mytable

Self contained complete examples are often useful.

<?php
  // The server where your database is hosted                 localhost
  // The name of your database                                mydatabase
  // The user name of the database user                       databaseuser
  // The password of the database user                        thesecretpassword
  // Most web pages are in utf-8 so should be the database    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
  try
  {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "databaseuser", "thesecretpassword", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));  
  }
    catch(PDOException $e)
  {
    die('Could not connect: ' . $e->getMessage());
  }

  $sql   = "SHOW COLUMNS FROM mytable";
  $query = $pdo->prepare($sql);
  $query->execute();

  $err = $query->errorInfo();
  $bug = $err[2];

  if ($bug != "") { echo "<p>$bug</p>"; }

  while ($row = $query->fetch(PDO::FETCH_ASSOC))
  {
    echo "<pre>" . print_r($row, true) . "</pre>";
  }

  /* OUTPUT SAMPLE  
  Array
  (
      [Field] => page_id
      [Type] => char(40)
      [Null] => NO
      [Key] => 
      [Default] => 
      [Extra] => 
  )

  Array
  (  
      [Field] => last_name
      [Type] => char(50)
      More ...
  */
?>
1
  • 1
    The OP did not tag this question with the php tag
    – Rotimi
    May 2, 2019 at 12:42
1
ResultSet rs = Sstatement.executeQuery("SELECT * FROM Table Name");

ResultSetMetaData rsMetaData = rs.getMetaData();

int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);

for (int i = 1; i <= numberOfColumns; i++) {
 System.out.println("column number " + i);

  System.out.println(rsMetaData.getColumnTypeName(i));
}
1
  • The OP did not tag this question with the java tag.
    – Rotimi
    May 2, 2019 at 12:41
1

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='SCHEMA_NAME' AND COLUMN_KEY='PRI'; WHERE COLUMN_KEY='PRI';

0
SELECT 
TABLE_CATALOG,
TABLE_SCHEMA,
TABLE_NAME, 
COLUMN_NAME, 
DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Dec 7, 2021 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.