CREATE, ALTER & DROP TABLE
Define tables, change them safely with ALTER TABLE, and understand what DROP does to the data and to the tables that depend on it.
The statements that shape the database
CREATE TABLE makes a table: you give it a name and, for each column, a name and a data type. ALTER TABLE changes a table that already exists: add, drop or rename a column, add or drop a rule, change a default. DROP TABLE removes a table and all its rows.
These are called DDL (data definition language) statements. They change the shape of the data, not the data inside it.
Software changes, so tables must too
No design survives the first year unchanged. A new feature needs a new column, an old column is renamed, a rule is added. Doing it with ALTER TABLE keeps the existing rows instead of starting again.
Add, rule, rename, drop
CREATE TABLE labels (
id integer PRIMARY KEY,
text text NOT NULL
);
ALTER TABLE products ADD COLUMN stock integer DEFAULT 0;
ALTER TABLE products ALTER COLUMN price SET NOT NULL;
ALTER TABLE products RENAME COLUMN name TO title;
ALTER TABLE products DROP COLUMN stock;When you add a column, every existing row gets the default, or NULL if you gave none. The products table keeps its three rows, and each now has stock = 0.
A new rule is checked against the rows that are already there. SET NOT NULL fails if any row has a NULL in that column: PostgreSQL says column "price" of relation "products" contains null values. Fix the data first, then add the rule. ADD UNIQUE likewise fails if two rows already share a value.
Change the shop database
Run ADD COLUMN price, then SET NOT NULL on price. Then try to drop products in both ways and compare what is left.
| idinteger | nametext |
|---|---|
| 10 | Notebook |
| 11 | Pen |
| 12 | Ruler |
| order_idinteger | product_idinteger |
|---|---|
| 101 | 10 |
| 101 | 11 |
| 103 | 12 |
Pick a statement and press Run statement. Try ADD COLUMN, then SET NOT NULL, then the two ways to drop products. Reset database starts again.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- CREATE TABLE defines a table. ALTER TABLE changes it. DROP TABLE removes it and all its rows.
- A new column is filled with its default, or with NULL if there is none.
- A new rule is checked at once against the existing rows, so bad data must be fixed first.
- DROP is refused when other objects depend on the table. CASCADE removes the dependent constraints, not the other tables.
Done with this concept?
Mark it complete to track your progress. No login needed.