Combined review · case study

CREATE TABLE and ALTER TABLE: SQL migration exercise

Decide whether you need a new structure or a migration of an existing table, and plan the change before touching real data.

35–40 minIntermediate levelFirst you need: data types, keys and constraints

Have a go before opening the examples

First you need: Create tables and choose data types, Declare primary and foreign keys, Protect columns with constraints, Modify tables with ALTER TABLE, Update rows with UPDATE. If any of the groundwork is missing, go back to that lesson and then carry on from here.

Complete each task, predict a row and explain the decision that produces it. Results are saved per activity.

Practice

Keep both rows during the migration

Not started

The suppliers table already holds ids 1 and 2. Add internal_code VARCHAR(12), set it to 'ND-01' for id 1 only, and return id, name and internal_code sorted by id.

We check the full final state: the change you were asked to make and that every other row is untouched. Review the output of each statement too.

The table for this activity is already set up. Look at its data; you do not need to create it again.

Every attempt resets the data, so include all the steps you need to check in a single attempt.

View tables and data

Open this panel to see the full data.

Run the full example in SQLite too

Download the prepared file. Open an empty SQLite database and import the file as a script. If you use the sqlite3 shell, type .read name-del-archivo.sql. Read the checking SELECTs in the order they appear in the file. To start again from scratch, open another empty database and import the same script again.

PRAGMA inspects the schema in SQLite and is not available in the teaching lab. The activities on this page already set up their own tables and reset the data on every attempt.

To finish: explain what a row represents, which requirement you checked and what would change if the rule changed.

See worked examples and checks

By the end, you will be able to

  • Choose between CREATE TABLE and ALTER TABLE.
  • Separate logical design from migration steps.
  • Recognise when an operation calls for engine-specific documentation.

The main decision

ScenarioStarting commandCheck question
The entity does not exist yet.CREATE TABLEWhich columns, types, keys and rules does it need from the start?
The table already exists and must evolve.ALTER TABLEWhich data, constraints, views or applications depend on the change?

Before migrating: take stock of the current state

A valid statement can still produce a wrong migration if it ignores the data and the dependencies. Before writing any SQL, write down at least:

  • the current table definition and its constraints;
  • the number of rows and whether there are null or duplicate values;
  • the views, indexes, foreign keys and queries that use the column;
  • the target state and an observable check that it succeeded;
  • a backup, rehearsal and recovery strategy that works with your engine.

A migration has two outcomes. It must leave a correct schema and keep the data correct. Checking only that the statement finished without an error proves neither.

Example: creating and extending a table

First, a small suppliers table is created. Later, a new need comes up: storing an optional phone number.

SQL
CREATE TABLE suppliers (
  id INTEGER PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(180) UNIQUE
);

INSERT INTO suppliers (id, name, email) VALUES
  (1, 'North Digital', 'ventas@northdigital.test'),
  (2, 'South Supplies', NULL);

ALTER TABLE suppliers
ADD COLUMN phone VARCHAR(30);

SELECT id, name, email, phone
FROM suppliers
ORDER BY id;

The new column is optional, so existing rows get NULL. The example keeps creation, data loading and schema changes apart; you can check each step before moving on.

Result after adding the column
idnameemailphone
1North Digitalsales@nortedigital.testNULL
2South SuppliesNULLNULL

Check data and structure separately

Checking the data
SELECT COUNT(*) AS pending_phones
FROM suppliers
WHERE phone IS NULL;

The result is 2. That figure is not an error: it describes the migration work still to do before the column can be made mandatory.

Even a small migration needs a plan

  1. Describe the current state and the target state.
  2. Check how many rows and dependencies may be affected.
  3. Review the syntax and limitations of the engine and its version.
  4. Rehearse on a copy and have a way to recover.
  5. Check data, constraints and queries after the change.

The operation determines the cost and the syntax

ChangeMain riskPortability
Adding an optional columnDependencies and the starting value of existing rowsCommon, with specific restrictions
Changing type or nullabilityConversion, validation and possibly rewriting the tableThe syntax varies a lot
Renaming or droppingBreaking queries, views or external codeCapabilities differ by version
Adding a key or constraintExisting data that breaks the new ruleMust be checked for each engine

PostgreSQL and MySQL support a wide range of ALTER TABLEoperations. SQLite documents a narrower set of direct operations; some changes require building a new table, copying the data across and replacing the old one. Always check the version you will actually deploy.

ALTER TABLE syntax is not fully portable. Adding a simple column is common, but changing types, defaults or constraints varies between PostgreSQL, MySQL, SQLite, SQL Server and Oracle.

Common mistake: mixing definition and data without checking

A constraint the current rows cannot meet

ALTER TABLE suppliers
ADD COLUMN country VARCHAR(80) NOT NULL;

If the table already contains rows, the engine needs to resolve the value of country for each one. A safer approach is usually to add the column as optional, fill in and validate the data, and apply the constraint in a later step that your engine supports.

Exercise: add a column without losing suppliers

Carry on with the suppliers table from the example. You need to store an optional internal code, set ND-01 for supplier 1 and leave the names and emails of both rows unchanged. Before opening the solution, write the structure change and the data change separately.

See solution and checks
SQL · SQLite
ALTER TABLE suppliers ADD COLUMN internal_code VARCHAR(12);

UPDATE suppliers
SET internal_code = 'ND-01'
WHERE id = 1;

SELECT id, name, email, internal_code
FROM suppliers
ORDER BY id;
Data preserved after migration
idnameemailinternal_code
1North Digitalsales@nortedigital.testND-01
2South SuppliesNULLNULL

ALTER TABLE adds the column to the structure and UPDATE fills in only the record you were asked for. Do not make up a value for supplier 2: NULL says that its code is not known yet.

SQL · SQLite
SELECT COUNT(*) AS suppliers,
       COUNT(internal_code) AS with_code
FROM suppliers;

PRAGMA table_info(suppliers);

The first query returns suppliers = 2 and with_code = 1. In SQLite, PRAGMA table_info should show internal_code with the declared type VARCHAR(12) and notnull = 0. Checking both separates keeping the data from creating the column correctly.

Run the exercise only once on the prepared table: repeating ADD COLUMN fails because the column already exists. In a real migration, keep a record of which changes have been applied. Also, SQLite does not enforce the limit of 12 in VARCHAR(12); if you need it, validate the length with a constraint or in the application. PRAGMA is specific to SQLite.

If you still mix up the operations, go back to creating tables from scratch and then to changing an existing table. This exercise combines both steps into a change you can verify.

Check what you have mastered

  • You can tell a new table apart from a change to existing data.
  • You define the starting state, the target state and an observable test of the change.
  • You do not apply a mandatory constraint without reviewing the existing rows.
  • You check the engine documentation before assuming that an ALTER TABLE operation is portable or reversible.

Key takeaways

  • CREATE TABLE defines a new structure; ALTER TABLE modifies an existing one. Modified
  • A migration affects both the definition and the data and its dependencies.
  • Differences between engines are part of the problem, not a side note.

Suggested path