Data Definition Language (DDL): Designing Schemas 🏗️
So far in this masterclass, we have focused on querying data using SELECT.
Now, we shift to the architecture side of SQL: How do we create the tables in the first place? How do we modify them as our app evolves?
In SQL, commands that define, alter, and delete database structures belong to DDL (Data Definition Language):
CREATE: Build a new table, database, or index.ALTER: Modify an existing table's schema (add/remove columns or constraints).DROP: Permanently destroy a table and all its data.TRUNCATE: Fast-wipe all rows from a table while preserving the schema.
1. Creating Tables with CREATE TABLE 🛠️
To create a table, you specify the table name, followed by a list of columns with their data types and optional integrity constraints:
CREATE TABLE users ( id SERIAL PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(150) NOT NULL UNIQUE, age INT CHECK (age >= 18), role VARCHAR(20) DEFAULT 'CUSTOMER', is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);Let's dissect the Constraints used here:
2. The 6 Essential SQL Constraints 🛡️
Constraints are business rules enforced directly by the database engine. If an application tries to write data that violates a constraint, the DBMS aborts the operation immediately.
| Constraint | Purpose | Example |
|---|---|---|
NOT NULL | Guarantees that a column cannot have missing/empty values | email VARCHAR(100) NOT NULL |
UNIQUE | Ensures all values in a column are distinct (no duplicates) | username VARCHAR(50) UNIQUE |
PRIMARY KEY | Combination of NOT NULL and UNIQUE. Uniquely identifies each row | id SERIAL PRIMARY KEY |
FOREIGN KEY | Enforces referential integrity pointing to a parent table | customer_id INT REFERENCES customers(id) |
CHECK | Validates that values satisfy a boolean logical expression | CHECK (price > 0 AND discount <= price) |
DEFAULT | Assigns an automatic default value if none is provided on insert | created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP |
The Power of CHECK Constraints:
CHECK constraints prevent corrupted business states from ever reaching your database:
CREATE TABLE accounts ( id SERIAL PRIMARY KEY, balance DECIMAL(12, 2) NOT NULL, account_type VARCHAR(10) CHECK (account_type IN ('SAVINGS', 'CURRENT')), CONSTRAINT non_negative_balance CHECK (balance >= 0.00));If a buggy backend API tries to set an account balance to -500, the DBMS rejects the write with a constraint violation!
3. Creating Tables with Foreign Keys & Cascade Actions 🔗
When linking tables with Foreign Keys, you can specify what should happen when a parent record is deleted:
CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, user_id INT NOT NULL, total_amount DECIMAL(10, 2) NOT NULL, order_date DATE DEFAULT CURRENT_DATE, -- Foreign Key definition with Cascade Rule: CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE);What does ON DELETE CASCADE mean?
ON DELETE CASCADE: If a user is deleted fromusers, the database automatically deletes all their orders inorders.ON DELETE RESTRICT/NO ACTION(Default): Rejects deleting the user if they still have orders.ON DELETE SET NULL: Keeps the orders, but sets theiruser_idtoNULL.
4. Modifying Existing Tables with ALTER TABLE 🔄
As your software application evolves, schemas change: you may need a new column, or you may need to drop an obsolete one.
You do not delete the table and start over—you use ALTER TABLE:
Adding a New Column:
ALTER TABLE users ADD COLUMN phone_number VARCHAR(20);Dropping an Obsolete Column:
ALTER TABLE users DROP COLUMN is_active;Renaming a Column:
ALTER TABLE users RENAME COLUMN email TO email_address;Adding a Constraint After Creation:
ALTER TABLE users ADD CONSTRAINT check_valid_email CHECK (email_address LIKE '%@%');5. Destroying Tables: DROP vs TRUNCATE 💥
When you need to remove data or tables entirely, SQL provides two distinct commands:
Command A: DROP TABLE (Deletes Schema + Data)
DROP TABLE orders;- Completely removes the entire table definition, schema, and all rows from disk.
- If you run
SELECT * FROM orders;afterward, the database reports:Table "orders" does not exist.
Safe Drop Pattern: Use
DROP TABLE IF EXISTS orders;to prevent SQL scripts from throwing errors if the table is already gone.
Command B: TRUNCATE TABLE (Fast Wipe of Data Only)
TRUNCATE TABLE orders;- Deletes all rows from the table in one lightning-fast operation.
- Keeps the table structure and columns intact so you can immediately insert new rows.
- Resets auto-incrementing serial IDs back to 1.
- Dramatically faster than
DELETE FROM table;because it doesn't log individual row deletions.
Flashcard Checkpoint 🎴
What is the critical difference between DROP TABLE and TRUNCATE TABLE?
TRUNCATE TABLE: Wipes all rows of data instantly, but preserves the empty table structure for future inserts.
What happens when a row is inserted without specifying a value for a column that has a DEFAULT constraint?
CURRENT_TIMESTAMP or 'CUSTOMER').