0

I need mysql script (not a stored procedure) that check whether column exist or not before altering the table.

Dhruv
  • 10,291
  • 18
  • 77
  • 126
  • See this http://stackoverflow.com/questions/3395798/mysql-check-if-a-column-exists-in-a-table-with-sql – abhinav Mar 05 '12 at 06:51

5 Answers5

2
SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'my_table' AND COLUMN_NAME = 'my_column'

If the above returns 0 rows, well, you know the column doesn't exist.

Ryan Kempt
  • 4,200
  • 6
  • 30
  • 41
2

Try this

SELECT * 
FROM information_schema.COLUMNS 
WHERE 
    TABLE_SCHEMA = 'db_name' 
AND TABLE_NAME = 'table_name' 
AND COLUMN_NAME = 'column_name'
Rupesh Pawar
  • 1,887
  • 12
  • 17
1

You can do it in this way

SHOW columns from `yourtable` where field='yourfield'
Mulesoft Developer
  • 2,664
  • 5
  • 28
  • 41
1

You can retrieve the existence of the field ...

SELECT * 
FROM information_schema.COLUMNS 
WHERE 
    TABLE_SCHEMA = 'your_db_name' 
AND TABLE_NAME = 'your_table_name' 
AND COLUMN_NAME = 'your_column_name'

...but you cannot add an ALTER-statement depending on the outcome. SQL just can't do that.

The place for that kind of logic is either in a stored procedure or in an application language.

Bjoern
  • 15,934
  • 4
  • 43
  • 48
0

Try this

function add_column_if_not_exist($db, $column, $column_attr ="VARCHAR(255) NULL")
{
    $exists = false;
    $columns = mysql_query("show columns from $db");
    while($c = mysql_fetch_assoc($columns)){
        if($c['Field'] == $column){
            $exists = true;
            break;
        }
    }      
    if(!$exists){
        mysql_query("ALTER TABLE `$db` ADD `$column`  $column_attr");
    }
}
Naveen Kumar
  • 4,543
  • 1
  • 18
  • 36