How can ALTER be used to drop a column in a MySQL table if that column exists?
I know I can use ALTER my_table DROP COLUMN my_column
, but that will throw an error if my_column
does not exist. Is there alternative syntax for dropping the column conditionally?
I'm using MySQL version 4.0.18.
There is no language level support for this in MySQL. Here is a work-around involving MySQL information_schema meta-data in 5.0+, but it won't address your issue in 4.0.18.
I wrote some more detailed information in a blog post.
For MySQL, there is none: MySQL Feature Request.
Allowing this is arguably a really bad idea, anyway:
IF EXISTS
indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.
MariaDB also supports the following starting with 10.0.2:
i. e.
But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.
I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...
x
DROPa
;any tables which had the table now haven't any tables which didn't will have shown an error in the logs
then you can find/replace 'drop
a
' change it to 'ADD COLUMNb
INT NULL' etc and run the whole thing again....a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.
Chase Seibert's answer works, but I'd add that if you have several schemata you want to alter the SELECT thus:
I just built a reusable procedure that can help making
DROP COLUMN
idempotent:Usage:
Example:
I know this is an old thread, but there is a simple way to handle this requirement without using stored procedures. This may help someone.
Hope this helps someone, as it did me (after a lot of trial and error).