MySQL, Check if a column exists in a table with SQL
Solution 1:
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;
Solution 2:
@julio
Thanks for the SQL example. I tried the query and I think it needs a small alteration to get it working properly.
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name'
That worked for me.
Thanks!
Solution 3:
Just to help anyone who is looking for a concrete example of what @Mchl was describing, try something like
SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'my_schema' AND TABLE_NAME = 'my_table'
AND COLUMN_NAME = 'my_column'`
If it returns false (zero results) then you know the column doesn't exist.
Solution 4:
I threw this stored procedure together with a start from @lain's comments above, kind of nice if you need to call it more than a few times (and not needing php):
delimiter //
-- ------------------------------------------------------------
-- Use the inforamtion_schema to tell if a field exists.
-- Optional param dbName, defaults to current database
-- ------------------------------------------------------------
CREATE PROCEDURE fieldExists (
OUT _exists BOOLEAN, -- return value
IN tableName CHAR(255), -- name of table to look for
IN columnName CHAR(255), -- name of column to look for
IN dbName CHAR(255) -- optional specific db
) BEGIN
-- try to lookup db if none provided
SET @_dbName := IF(dbName IS NULL, database(), dbName);
IF CHAR_LENGTH(@_dbName) = 0
THEN -- no specific or current db to check against
SELECT FALSE INTO _exists;
ELSE -- we have a db to work with
SELECT IF(count(*) > 0, TRUE, FALSE) INTO _exists
FROM information_schema.COLUMNS c
WHERE
c.TABLE_SCHEMA = @_dbName
AND c.TABLE_NAME = tableName
AND c.COLUMN_NAME = columnName;
END IF;
END //
delimiter ;
Working with fieldExists
mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_option', NULL) //
Query OK, 0 rows affected (0.01 sec)
mysql> select @_exists //
+----------+
| @_exists |
+----------+
| 0 |
+----------+
1 row in set (0.00 sec)
mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_options', 'etrophies') //
Query OK, 0 rows affected (0.01 sec)
mysql> select @_exists //
+----------+
| @_exists |
+----------+
| 1 |
+----------+
Solution 5:
Following is another way of doing it using plain PHP without the information_schema database:
$chkcol = mysql_query("SELECT * FROM `my_table_name` LIMIT 1");
$mycol = mysql_fetch_array($chkcol);
if(!isset($mycol['my_new_column']))
mysql_query("ALTER TABLE `my_table_name` ADD `my_new_column` BOOL NOT NULL DEFAULT '0'");