MySQL, Check if a column exists in a table with SQL

clops picture clops · Aug 3, 2010 · Viewed 219.9k times · Source

I am trying to write a query that will check if a specific table in MySQL has a specific column, and if not — create it. Otherwise do nothing. This is really an easy procedure in any enterprise-class database, yet MySQL seems to be an exception.

I thought something like

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
           WHERE TABLE_NAME='prefix_topic' AND column_name='topic_last_update') 
BEGIN 
ALTER TABLE `prefix_topic` ADD `topic_last_update` DATETIME NOT NULL;
UPDATE `prefix_topic` SET `topic_last_update` = `topic_date_add`;
END;

would work, but it fails badly. Is there a way?

Answer

Mfoo picture Mfoo · Sep 1, 2011

This works well for me.

SHOW COLUMNS FROM `table` LIKE 'fieldname';

With PHP it would be something like...

$result = mysql_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'");
$exists = (mysql_num_rows($result))?TRUE:FALSE;