Adding a new column to a MySQL table will put it at the end of the table. When adding a new column to a table you sometimes want to place it at a given position, next to an existing column in the table.
MySQL allows you to place a new column after an existing one using the AFTER <column-name>
syntax. Read on to get more details.
MySQL Series Overview
Add a New Field After an Existing Column in a MySQL Table
Use the ALTER TABLE … ADD COLUMN
syntax in MySQL to add a new column. This command supports the AFTER
keyword telling MySQL to add a new column after an existing one.
Here’s a sample SQL query that adds a new fullname
column after the existing lastname
:
ALTER TABLE users
ADD COLUMN fullname VARCHAR(150) NULL AFTER lastname;
You can add multiple columns in a single statement and combine the creation with the AFTER
syntax as well. Every new column defines their position using AFTER
:
ALTER TABLE users
ADD COLUMN uuid VARCHAR(50) NULL AFTER id
ADD COLUMN fullname VARCHAR(150) NULL AFTER uuid;
That’s it!