Add column after another column in MySQL by Josh Sherman

0
19

By default, new columns are added to the end of a table in MySQL. This works well most of the time, but sometimes when you’re retrofitting a column into a table, you may want it to be adjacent columns closer to the start of the table.

The ALTER statement makes it easy to add a column anywhere in a table, by adding AFTER at the end of the ADD COLUMN query. A query adding a single column after another column looks like this:

ALTER TABLE `table`
ADD COLUMN `new_column` VARCHAR(255) NOT NULL
AFTER `existing_column`;

You can adjust the column definition however you see fit.

This also works if you’re adding multiple columns, even allowing you to reference columns you’re about to add and not just columns that already exist on the table:

ALTER TABLE `table`
ADD COLUMN `new1` VARCHAR(255) NOT NULL AFTER `existing`,
ADD COLUMN `new2` VARCHAR(255) NOT NULL AFTER `new1`;

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here