Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL retrieve column names where datatype == X

I need to write some code that applies to only certain fields within our database. Specifically I'm looking for any field in all tables of a single database that are of type DECIMAL(12,5);

If it's of any help, all of our decimal fields are prefixed with dec_. I could gather all of the decimal fields from all tables, but there are tons of them that don't match my particular criteria, I need only the decimal values who's limit is 12,5.

I'd have no preference between doing this in pure SQL, or using PHP. We're currently using the CakePHP framework to manage our project, though I could just as easily do this without using the framework. This is a one time operation to gather the required data so I can continue forward with the audit.

Any help is greatly appreciated, thank you for taking the time to read this.

[EDIT] Got some great answers here, thanks everyone! I probably should have mentioned this in my initial post, but is there any way I can also get the table name associated with each field?

like image 268
Zetaphor Avatar asked Aug 24 '11 15:08

Zetaphor


People also ask

How do I get column names in MySQL?

You can list a table's columns with the mysqlshow db_name tbl_name command. The DESCRIBE statement provides information similar to SHOW COLUMNS .

How can I get column names and datatypes of a table in MySQL?

You can get the MySQL table columns data type with the help of “information_schema. columns”. SELECT DATA_TYPE from INFORMATION_SCHEMA. COLUMNS where table_schema = 'yourDatabaseName' and table_name = 'yourTableName'.

Which query can be used to retrieve the column name?

We can verify the data in the table using the SELECT query as below. We will be using sys. columns to get the column names in a table. It is a system table and used for maintaining column information.

How do I find a specific column in a MySQL database?

How to list all tables that contain a specific column name in MySQL? You want to look for tables using the name of columns in them. SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA. COLUMNS WHERE COLUMN_NAME IN('column1', 'column2') AND TABLE_SCHEMA = 'schema_name';


2 Answers

SELECT
    TABLE_NAME,
    COLUMN_NAME
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    TABLE_SCHEMA = 'db-name' AND
    DATA_TYPE = 'decimal' AND
    NUMERIC_PRECISION = 12 AND
    NUMERIC_SCALE = 5
like image 176
AlienWebguy Avatar answered Oct 21 '22 04:10

AlienWebguy


You can try to use the following approach:

$pdo = new PDO(...);

$sql = "select column_name from 
    information_schema.columns 
    where table_schema='$your_db' and table_name='?' and  data_type = 'decimal(12,5)'";

foreach($pdo->query("SHOW TABLES;") as $table) {
    $prepared = $pdo->prepare($sql);
    $prepared->execute(array($table));
    print_R($prepared->fetchAll()) ;  
}
like image 41
Andrej Ludinovskov Avatar answered Oct 21 '22 05:10

Andrej Ludinovskov