Sub topic 1
DDL: Statements That Change the Schema
Prerequisites
This chapter assumes you can write SELECT, INSERT, UPDATE and DELETE statements, that you have used CREATE TABLE, and that you understand primary and foreign keys. You need a test database such as PostgreSQL, MySQL, SQL Server or SQLite. The examples use PostgreSQL syntax unless noted.
What DDL Does
DDL (Data Definition Language) is the part of SQL that changes the structure of a database. CREATE, ALTER and DROP are DDL statements. DML (Data Manipulation Language) changes the rows inside tables. INSERT, UPDATE and DELETE are DML statements.
flowchart TD
A[CREATE TABLE defines structure] --> B[ALTER TABLE changes structure]
B --> C[INSERT UPDATE DELETE change rows]caption: Schema statements define and change structure, and row statements then fill that structure. alt: A three-step flow. CREATE TABLE leads to ALTER TABLE, which leads to row statements.
Anatomy of an ALTER TABLE Statement
Every ALTER TABLE statement names a table, then names one action to perform on it.
ALTER TABLE customers ADD COLUMN email VARCHAR(255);The pattern is ALTER TABLE table_name action. Common actions include ADD COLUMN, DROP COLUMN and ALTER COLUMN.
Adding a Column
New columns are allowed to hold NULL by default, so existing rows stay valid. A NOT NULL column with a default value works on a table that already has rows:
ALTER TABLE customers
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';Without the DEFAULT, the database cannot fill existing rows and rejects the statement.
Setting Defaults and NOT NULL
Use ALTER COLUMN to change rules on a column that already exists:
ALTER TABLE customers ALTER COLUMN status SET DEFAULT 'pending';
ALTER TABLE customers ALTER COLUMN email SET NOT NULL;SET NOT NULL fails if any row holds NULL in that column. Update those rows first.
> Note: MySQL uses MODIFY COLUMN, and SQL Server omits the COLUMN keyword in ADD. Check your dialect before running a script.
Dropping a Column
DROP COLUMN removes the column and every value stored in it:
ALTER TABLE customers DROP COLUMN email;This change cannot be undone by the database. Take a backup first.
Exercise
Exercise
You add status VARCHAR(20) NOT NULL to a customers table that already has 500 rows, without a DEFAULT. What happens, and how do you fix it?
Show answer
The database rejects the statement because existing rows would receive NULL in a NOT NULL column. Add a DEFAULT, such as ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active', so the existing rows receive a value.