Sub topic 2
Anatomy of an ALTER TABLE Statement
This chapter assumes you can write basic SELECT, INSERT, UPDATE and DELETE statements, and that you know CREATE TABLE, common data types, and primary and foreign keys. You should have a test database available (PostgreSQL, MySQL, SQL Server or SQLite). The examples use PostgreSQL unless a note says otherwise.
What ALTER TABLE does
ALTER TABLE changes the definition of a table that already exists. It is a Data Definition Language (DDL) statement. It edits the schema, which is the description of the table, and it leaves the rows to the database to carry along. Later chapters cover each kind of change in detail. This chapter explains the structure they all share, so that you can read any ALTER TABLE statement and predict what it does.
The alternative to ALTER TABLE is to create a new table, copy the data across, drop the old table and rename the new one. That works, but it is slow and easy to get wrong. ALTER TABLE keeps the table's name, its data, and the objects that point at it, such as indexes and foreign keys.
The general shape
Every ALTER TABLE statement has the same three layers:
- The keywords
ALTER TABLEand the name of the table. - An action keyword, such as
ADD,DROP,ALTER,MODIFYorRENAME. - The target of the action and its new definition.
ALTER TABLE customers ADD COLUMN email VARCHAR(255);Here customers is the table, ADD COLUMN is the action, email is the target, and VARCHAR(255) is the definition. The statement reads almost like a sentence, and most statements you meet follow this pattern.
Not every action needs every part. A DROP COLUMN needs only a target, because there is nothing left to define. A RENAME COLUMN needs an old name and a new name instead of a definition.
The common actions
The table below lists the actions you will use most. The following chapters treat each in turn.
| Goal | Typical form | Target |
|---|---|---|
| Add a column | `ADD COLUMN name type` | A new column |
| Remove a column | `DROP COLUMN name` | An existing column |
| Change a column | `ALTER COLUMN name ...` or `MODIFY COLUMN ...` | An existing column |
| Rename a column | `RENAME COLUMN old TO new` | An existing column |
| Rename a table | `RENAME TO new_name` | The table itself |
| Add a rule | `ADD CONSTRAINT name ...` | A constraint |
| Remove a rule | `DROP CONSTRAINT name` | A named constraint |
Notice that the verb tells you whether you are creating something new (ADD), removing something (DROP), or changing something that exists (ALTER, MODIFY, RENAME). The same word can have different effects depending on what follows it. ALTER COLUMN changes a column's definition, and ALTER TABLE is the statement that contains it.
A first complete example
This script creates a table, changes it, and then inspects the result. You can run it as shown in PostgreSQL.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
INSERT INTO customers (id, name) VALUES (1, 'Ada'), (2, 'Grace');
ALTER TABLE customers ADD COLUMN email VARCHAR(255);
SELECT id, name, email FROM customers;The final query returns both rows, and email is NULL in each of them. This shows what ADD COLUMN does to existing data. The table gains the column, every existing row receives the column's default value, and a column with no declared default gets NULL. Because the default here is NULL, the column must be nullable. Adding a NOT NULL column to a table that already has rows needs a default, which a later chapter covers.
Combining several actions
Often you want to make several changes to one table. Most databases let you list them in one statement, separated by commas.
ALTER TABLE customers
ADD COLUMN phone VARCHAR(30),
ADD COLUMN country CHAR(2);In PostgreSQL and MySQL, a single statement is applied as a unit. If one action fails, none of them takes effect, and the table keeps its old definition. A single statement also lets the database rewrite the table once instead of twice, which matters on large tables.
The rule is not universal:
- SQL Server writes
ADDonce and lists the columns after it, with no repeated keyword and noCOLUMN. - SQLite accepts only one action per
ALTER TABLEstatement, so you issue a separate statement for each change. - Oracle puts the new columns in parentheses:
ADD (phone VARCHAR2(30), country CHAR(2)).
-- SQL Server
ALTER TABLE customers
ADD phone VARCHAR(30),
country CHAR(2);Where the dialects differ
ALTER TABLE is standardized in outline, but the details vary. The variation is larger than for SELECT, and it is a common cause of scripts that work on a laptop and fail in production.
| Detail | PostgreSQL | MySQL | SQL Server | SQLite |
|---|---|---|---|---|
| `COLUMN` keyword in `ADD` | Optional | Optional | Not allowed | Optional |
| Change a column type | `ALTER COLUMN ... TYPE` | `MODIFY COLUMN` | `ALTER COLUMN` | Not supported |
| Rename a column | `RENAME COLUMN` | `RENAME COLUMN` (8.0+) | `sp_rename` | `RENAME COLUMN` (3.25+) |
| Several actions in one statement | Yes | Yes | Partly | No |
Before running a script on an unfamiliar database, check the documentation for that product and version. This habit prevents most dialect errors.
Reading the result
After a change, confirm what the table now looks like. The information_schema views are part of the SQL standard and exist in PostgreSQL, MySQL and SQL Server.
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'customers'
ORDER BY ordinal_position;In PostgreSQL's psql client, \d customers gives a shorter view. In MySQL, use DESCRIBE customers;. In SQLite, use PRAGMA table_info(customers);.
Common errors at this level
Most failures of ALTER TABLE fall into a few groups:
- The table does not exist. The error names the missing table. Check the schema or database you are connected to, and any spelling or case differences.
- The column already exists. Running an
ADD COLUMNscript twice produces this error. Some databases offerADD COLUMN IF NOT EXISTS(PostgreSQL does), but MySQL and SQL Server do not. - Reserved words. A column named
orderorgroupmust be quoted: double quotes in PostgreSQL and SQLite, backticks in MySQL, square brackets or double quotes in SQL Server. Avoiding such names is easier. - Existing data violates the new definition. Adding
NOT NULLor a constraint fails if any current row breaks the rule. The database checks all rows first and refuses the change. - Dependencies. Views, indexes, foreign keys and other objects can block a change to a column they use. A later chapter explains this.
Summary of the structure
An ALTER TABLE statement names a table, picks an action, identifies a target, and gives a new definition when one is needed. Several actions can often be combined with commas, but not in every database. Existing rows are carried along, and new columns are filled with their default or with NULL. Check the dialect before running a script elsewhere, and verify the result with the catalog views.
Exercise
You run ALTER TABLE customers ADD COLUMN country CHAR(2); on a table that already holds 500 rows, and then run SELECT country FROM customers;. What do the 500 rows contain in country, and why? Then explain what would need to change if the column were declared NOT NULL.
Show answer
All 500 rows contain NULL, because the column has no default and the database gives existing rows the column's default, which is NULL when none is declared. If the column were declared NOT NULL, the statement would fail on a table with existing rows unless it also had a DEFAULT, for example ADD COLUMN country CHAR(2) NOT NULL DEFAULT 'US', so that the existing rows receive a valid value.
Exercise
Rewrite ALTER TABLE customers ADD COLUMN phone VARCHAR(30), ADD COLUMN country CHAR(2); so that it runs on SQL Server, and say how you would run the equivalent changes in SQLite.
Show answer
SQL Server: ALTER TABLE customers ADD phone VARCHAR(30), country CHAR(2);, with no COLUMN keyword and ADD written once. SQLite accepts only one action per statement, so you run two statements: ALTER TABLE customers ADD COLUMN phone VARCHAR(30); and ALTER TABLE customers ADD COLUMN country CHAR(2);.