In the previous tutorial, we looked at adding a new column after an existing column in MySQL. That tutorial showed you how to add a new column at any position in a table, except the first.
In this tutorial, we’re adding a new column to the beginning of a table using the ALTER TABLE … ADD COLUMN … FIRST
syntax.
MySQL Series Overview
Adding a New First Column in a MySQL Table
MySQL allows you to add a new column to the beginning of a table. Use the ALTER TABLE … ADD COLUM
query to add a new column. Then put the FIRST
modified after the column name to make it the new, first column of that table.
Here’s an example of adding a new uuid
column to the beginning of the table. This new uuid
column pushes all other columns to their position:
ALTER TABLE users
ADD COLUMN uuid VARCHAR(50) FIRST;
You may add more than one column to your table and combine the positions as you want. For example, add a new column to the beginning and add another column after a given column in the table.
ALTER TABLE users
ADD COLUMN uuid VARCHAR(50) FIRST
ADD COLUMN fullname VARCHAR(150) NULL AFTER lastname
ADD COLUMN updatedon DATETIME;
The statement above adds the following fields to the users
table:
- a new first uuid
column
- a fullname
column after the existing lastname
column
- an updatedon
column at the end, as the new last column in the table
That’s it!
Mentioned Resources
- Future Studio tutorial on adding a new MySQL column after an existing one