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.
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
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.
The setup is already done: do not create the table again.
Add an optional attribute and limit the UPDATE by id.
The final SELECT checks both the new value and the NULL that was kept.
Solution explained
ALTER TABLE suppliers ADD COLUMN internal_code VARCHAR(12); UPDATE suppliers SET internal_code='ND-01' WHERE id=1; SELECT id,name,internal_code FROM suppliers ORDER BY id;The optional column leaves NULL on id 2. Changing id 1 neither deletes nor replaces any row.
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 TABLEandALTER TABLE. - Separate logical design from migration steps.
- Recognise when an operation calls for engine-specific documentation.
The main decision
| Scenario | Starting command | Check question |
|---|---|---|
| The entity does not exist yet. | CREATE TABLE | Which columns, types, keys and rules does it need from the start? |
| The table already exists and must evolve. | ALTER TABLE | Which 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.
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.
| id | name | phone | |
|---|---|---|---|
| 1 | North Digital | sales@nortedigital.test | NULL |
| 2 | South Supplies | NULL | NULL |
Check data and structure separately
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
- Describe the current state and the target state.
- Check how many rows and dependencies may be affected.
- Review the syntax and limitations of the engine and its version.
- Rehearse on a copy and have a way to recover.
- Check data, constraints and queries after the change.
The operation determines the cost and the syntax
| Change | Main risk | Portability |
|---|---|---|
| Adding an optional column | Dependencies and the starting value of existing rows | Common, with specific restrictions |
| Changing type or nullability | Conversion, validation and possibly rewriting the table | The syntax varies a lot |
| Renaming or dropping | Breaking queries, views or external code | Capabilities differ by version |
| Adding a key or constraint | Existing data that breaks the new rule | Must 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
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;| id | name | internal_code | |
|---|---|---|---|
| 1 | North Digital | sales@nortedigital.test | ND-01 |
| 2 | South Supplies | NULL | NULL |
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.
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 TABLEoperation is portable or reversible.
Key takeaways
CREATE TABLEdefines a new structure;ALTER TABLEmodifies 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.