How can ALTER be used to drop a column in a MySQL table if that column exists?
I know I can use ALTER TABLE 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.
The syntax goes like this: ALTER TABLE table_name DROP COLUMN column_name; Some RDBMSs accept an optional IF EXISTS argument which means that it won't return an error if the column doesn't exist.
The column Extension existing in the refreshed list is verification that it exists. To drop the Extensions column, we simply right click on it and delete as before. There are a couple of ways to drop it programmatically with T-SQL depending on which version of SQL Server you are on.
The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows. ALTER TABLE table_name DROP COLUMN column_name; The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as follows.
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:
DROP [COLUMN] [IF EXISTS] col_name
i. e.
ALTER TABLE my_table DROP IF EXISTS my_column;
But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With