How do you insert a new column at the beginning of a MySQL table?

And more importantly, why would you want to?

Joel Clermont
Joel Clermont
2023-10-09

Previously, I shared some potential performance issues with inserting a column at a specific position in an existing table.

This ordering is done by using the AFTER modifier for the ALTER COLUMN statement. But this raises an interesting question? What if you want to insert a column as the first column? There's nothing to put it "after".

For this use case, you can use the FIRST modifier instead of AFTER:

ALTER TABLE `orders` ADD COLUMN `id` INT(11) FIRST;

When might you actually use this? It's handy if you're working with a legacy database schema and normalizing it to Eloquent conventions. Maybe the legacy table had no primary key at all, so you want to add id as the first column.

Here to help,

Joel

P.S. You think this tip is good? You should try our free book of even more Laravel tips to make your application a little bit better.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.