Explain Codes LogoExplain Codes Logo

Adding a column after another column within SQL

sql
data-types
alter-table
database-management
Alex KataevbyAlex Kataev·Jan 28, 2025
TLDR

Here's a rapid way to add a new column into your SQL table: use ALTER TABLE combined with AFTER. In a MySQL scenario, you can add new_column right after existing_column with the following code:

ALTER TABLE your_table ADD COLUMN new_column VARCHAR(255) AFTER existing_column;

The trick above allows new_column to find its place neatly after existing_column. Keep in mind: AFTER is a MySQL luxury. Other DBMS have their own specific syntax.

Quick insights - what you need to know

Decisions on data types

A column isn't merely about order and names—the kind of data it holds is crucial too. Choose a suitable data type like INT, VARCHAR, DATE, or even more complex ones like ENUM and SET.

What if AFTER isn’t available?

For MS SQL Server users: yes, you can ADD columns, but unfortunately not AFTER a specific one. Your savior here would be management tools or SELECT statements manipulations.

Harmonizing with constraints

Adding a column also means adding responsibilities. It needs to obey the rules of your data kingdom defined by constraints like FOREIGN KEY, UNIQUE, and NOT NULL.

Deep into the rabbit hole

On changing column names

Indeed, with ALTER TABLE you aren’t just limited to ordering—you can rename columns too! Just like changing labels on spice jars—not too often, not the wrong ones!

Testing first, deploying next

When you’re ready to launch your changes, hold your horses! First, create a clone of your production in a development environment. You wouldn’t want a 'DROP' bomb exploding in your production data, right?

The power of documentation

Don’t forget to take notes of your ALTER TABLE adventures. This way, future you or another developer can thank past you. No need to memorize—it's like the magic-spell book that Hermione always had on hand.