How to delete a column from a table in MySQL?

MySQLMySQLi Database

We can delete a column from a table with the help of ALTER command. Let’s say we have create a table and have a requirement to deleted some columns in it. We can achieve this using the ALTER and DRO[ command.

Let us see an example. First, we will create a table.

mysql> create table DeleteColumnNameDemo
   -> (
   -> Id int,
   -> Name varchar(200),
   -> Age int,
   -> Address varchar(200)
   -> );
Query OK, 0 rows affected (0.59 sec)

Above, we have created a table with four columns. Here is the query through which we can see all the details about the table.

mysql> desc DeleteColumnNameDemo;

The following is the output.

+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| Id      | int(11)      | YES  |     | NULL    |       |
| Name    | varchar(200) | YES  |     | NULL    |       |
| Age     | int(11)      | YES  |     | NULL    |       |
| Address | varchar(200) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

Now we have 4 columns in our table. Now let us see the syntax to delete a column. The syntax is as follows.

alter table yourTableName
drop column yourColumnName1,
drop column yourColumnName2,
.
.
.
drop column yourColumnNameN,

Now, let us delete the column “Age” and “Address” from “DeleteColumnNameDemo” table. Apply the above syntax to delete the columns. The query is as follows.

mysql> ALTER table DeleteColumnNameDemo
   -> drop column Age,
   -> drop column Address;
Query OK, 0 rows affected (3.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

We have deleted both the columns, Age and Address from the table. Let us now check the columns have been deleted or not with the help of DESC command.

mysql> desc DeleteColumnNameDemo;

The following is the output. We cannot see the two columns “Age’ and “Address” because we have deleted the before.

+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Id    | int(11)      | YES  |     | NULL    |       |
| Name  | varchar(200) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.05 sec)
raja
Published on 30-Nov-2018 11:13:19
Advertisements