The MySQL Column-Existence Check That Sent Me Through Thirty Answers

Editorial illustration.

Originally published 16 June 2023; rewritten and reviewed on 15 October 2026.

When I wrote the original article, I had searched through more than thirty answers while trying to solve what seemed like a small problem: check whether a column exists before adding it in MySQL. The examples often required more surrounding procedure code than I expected.

The later update to that post introduced another problem: it presented ADD COLUMN IF NOT EXISTS as though it were valid for MySQL 5.7. It should not be copied into that version’s migration.

Ask the database about its schema

A read-only check for a known table and column is straightforward:

SELECT COUNT(*) AS matching_columns
FROM information_schema.columns
WHERE table_schema = DATABASE()
  AND table_name = 'orders'
  AND column_name = 'external_reference';

Use the intended schema explicitly if the connection has no selected database. When the names originate from application values, bind them as values in the metadata query rather than concatenating them into SQL.

Let a controlled migration make the change

If the column is absent, apply the reviewed ALTER TABLE through the project’s migration process. A metadata check followed by DDL is not automatically atomic: two deployment processes can race. Serialize migrations or handle the expected already-present condition deliberately.

Identifiers in a DDL statement are a separate concern from query values. Keep them fixed or validate them against a controlled schema definition; a value parameter is not a general substitute for a table name.

Consult the MySQL 5.7 ALTER TABLE reference for that historical version. Do not transfer syntax from a different server product merely because the names look similar.

Verify more than existence

A column can exist with the wrong type, default or nullability. Compare the intended definition and test the application’s read and write behaviour after the migration. The lesson is to turn a quick existence check into a repeatable schema change whose assumptions are visible.

Related reading