Done!

Adding new column on a large SQL Database table


Just Using ALTER column on a huge database table to add a new column can significantly slow down the performance and can even bring the database down.

In this scenario, the best way to add new column is to create a new table, add new column on this new table, migrate data from old table to new table and finally rename or delete old table and rename newly created table with new column into a original table. Steps are as below.

1. Create a new database table from the original employee table

CREATE TABLE employee_new LIKE employee;

2. Add a new column into a new employee_new database table.

ALTER TABLE employee_new ADD employee_member_id int(11) NULL;

3. Migrate data to new table

INSERT into employee_new
 (
    employee_id,
    employee_name,
    employee_address
 )
SELECT
    employee_id,
    employee_name,
    employee_address
FROM employee ;

4. Start a transaction to rename the new table to original one and viceversa

START TRANSACTION;
    INSERT into employee_new
     (
        employee_id,
        employee_name,
        employee_address
     )
    SELECT
        employee_id,
        employee_name,
        employee_address
    FROM employee
    WHERE employee_id > (SELECT max(employee_id) FROM employee_new);

    RENAME TABLE employee TO employee_old;

    RENAME TABLE employee_new TO employee;
COMMIT;