Thursday 12 July 2018

MySQL DROP COLUMN

MySQL DROP COLUMN?

Summary: in this tutorial, we will show you how to drop a column from a table using the MySQL DROP COLUMN statement.

Introduction to MySQL DROP COLUMN statement

In some situations, you want to remove one or more columns from a table. In such cases, you use the ALTER TABLE DROP COLUMN statement as follows:
Let’s examine the statement in more detail:
  • First, you specify the table that contains the column you want to remove after the ALTER TABLEclause.
  • Second, you put the name of the column following the DROP COLUMN clause.
Note that the keyword COLUMN is optional so you can use the shorter statement as follows:
To remove multiple columns from a table at the same time, you use the following syntax:
There are some important points you should remember before you remove a column from a table:
  • Removing a column from a table makes all database objects such as stored procedures, views, triggers, etc., that depend on the column invalid. For example, you may have a stored procedure that references to a column. When you remove the column, the stored procedure will become invalid. To fix it, you have to manually change the stored procedure’s code manually.
  • The code from other applications that depends on the removed column must be also changed, which takes time and efforts.
  • Removing a column from a large table can impact the performance of the database.

MySQL DROP COLUMN examples

First, we create a table named posts for the demonstration.
Second, to remove the excerpt column, you use the ALTER TABLE statement as follows:
Third, to remove both created_at and updated_at columns at the same time, you use the following statement:

MySQL drop a column which is a foreign key example

If you remove the column that is a foreign key, MySQL will issue an error. Let’s demonstrate the idea.
First, create a table named categories:
Second, add the category_id column to the posts table.
Third, make the category_id column as a foreign key that references to the id column of the categories table.
Fourth, drop the category_id column from the posts table.
MySQL issued an error message:
To avoid this error, you must remove the foreign key constraint before dropping the column.
In this tutorial, we have shown you how to use MySQL DROP COLUMN statement to remove one or more columns from a table.

0 comments:

Post a Comment