Friday, 14 February 2014

MySQL: Add multiple columns to a table

How to add a column to an existing MySQL table. For example a table is created using the following query:

CREATE TABLE CUSTOMER (
account_number int  NOT NULL PRIMARY KEY,
date DATE,
name VARCHAR(20) NOT NULL,
address VARCHAR(60) NOT NULL,
advance INT,
nic_number VARCHAR(20)
);

Now execute the explain customer query:


The table has to be altered to include telephone, connection_type and connection_fee fields.


ALTER TABLE customer
    ADD COLUMN telephone int,
    ADD COLUMN connection_type VARCHAR(15),
    ADD COLUMN connection_fee int;

Now re-executing the explain customer query yields:



Similarly in order to add one column following query will work:

ALTER TABLE customer ADD COLUMN telephone int;

It can be mentioned that where this column should be added. If a new column need to be added before connection_fee and after connection_type, it can be mentioned using after keyword.

ALTER TABLE customer ADD COLUMN newField int AFTER connection_type;


No comments:

Post a Comment