Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ALTER to drop a column if it exists in MySQL

Tags:

mysql

ddl

mysql4

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.

like image 376
jcodeninja Avatar asked Oct 06 '08 10:10

jcodeninja


People also ask

How do I drop a column if exists?

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.

How do you delete a column that exists in SQL?

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.

Which command is used to drop an existing column?

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.


1 Answers

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.

like image 175
Matthias Winkelmann Avatar answered Sep 23 '22 20:09

Matthias Winkelmann