MySQL ALTER TABLE

ALTER TABLE changes the structure of a table that already exists, without losing its data.

Add a column

ALTER TABLE students ADD COLUMN email VARCHAR(100);
MySQL says

Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0

Existing rows get NULL in the new column. You can choose the place with AFTER name or FIRST.

ALTER TABLE students ADD COLUMN phone VARCHAR(15) AFTER name;

Change the data type of a column

ALTER TABLE students MODIFY COLUMN email VARCHAR(150) NOT NULL DEFAULT '';

Rename a column

ALTER TABLE students RENAME COLUMN phone TO mobile;

Drop a column

ALTER TABLE students DROP COLUMN email;
ALTER TABLE students DROP COLUMN mobile;
Note: Dropping a column deletes its data for ever. We dropped the two test columns here, so the table is the same as before.

Rename the table

RENAME TABLE students TO pupils;
RENAME TABLE pupils TO students;

Add and remove constraints

ALTER TABLE students ADD UNIQUE (name);        -- if names must be unique
ALTER TABLE students ADD FOREIGN KEY (course_id) REFERENCES courses(id);

Summary

  • ADD COLUMN, MODIFY COLUMN, RENAME COLUMN and DROP COLUMN change the columns.
  • RENAME TABLE renames the table.
  • Next: MySQL Aliases.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a query to get all column names of a database table
Write a query to create a new table with the data and structure of another table
Interview Questions & Answers
Write a query to create a new table which consists of data and structure copied from the other table
What is a primary key in MySQL?
What is a foreign key in MySQL?
What is the difference between CHAR and VARCHAR in MySQL?
What is normalization in MySQL?
What is AUTO_INCREMENT in MySQL?
What is the difference between primary key and unique key?