Creating Tables in SQL
Turn a logical design into CREATE TABLE statements with primary keys, foreign keys, NOT NULL, UNIQUE, CHECK and DEFAULT, and spot common DDL mistakes.
Welcome back!
Step 1 of 15Learn
The language of structure
SQL has two halves. The data definition language (DDL) creates and changes structure: CREATE TABLE, ALTER TABLE, DROP TABLE. The data manipulation language (DML) works with rows: SELECT, INSERT, UPDATE, DELETE. A designer's output ends up as DDL.
Here is the customer table from the bookstore design:
CREATE TABLE customer (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
city VARCHAR(80),
created_at DATE NOT NULL DEFAULT CURRENT_DATE
);Every line records a design decision. customer_id is the primary key, so it is unique and never null. name and email are required. email is an alternate key, so it is UNIQUE. city is optional and may be NULL. created_at fills itself in when an insert doesn't supply it.
Exact syntax varies a little between systems. Auto-generated ids, for example, are written GENERATED ALWAYS AS IDENTITY in standard SQL and PostgreSQL, AUTO_INCREMENT in MySQL, and come automatically with INTEGER PRIMARY KEY in SQLite. The concepts carry over unchanged; check your DBMS's documentation for the spelling.
Step 2 of 15Practice · Diagram
The two halves of SQL
Adding a phone column to an existing table uses which command?
Tap the shape that answers the question, then press Check.
- SQL
- DDL: structure
What a designer writes.
- DML: rows
What applications run all day.
- CREATE
- ALTER
- DROP
- SELECT
- INSERT
- UPDATE
- DELETE
Step 3 of 15Practice · Code challenge · SQL
Code challenge · SQL
Create a table named book with three columns:
- book_id: integer primary key
- title: text, required (NOT NULL)
- price: a number, required (NOT NULL)
The checker inspects the columns of your table: name, whether it is required, and the primary key (a primary key counts as required).
The database for this exercise (tables and rows)
-- An empty database: your CREATE TABLE statement builds the first table.
SELECT 1;- Result matches the expected table
Step 4 of 15Practice · Fill in the blanks
Fill in the blanks
In a CREATE TABLE statement, the constraint that forbids missing values is , and the constraint that forbids two rows from sharing a value without making the column the primary key is .
Step 5 of 15Learn
Foreign keys and table-level constraints
Constraints that involve several columns, or that refer to other tables, are often written after the column list:
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
order_date DATE NOT NULL,
customer_id INTEGER NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customer (customer_id)
ON DELETE RESTRICT
);
CREATE TABLE order_line (
order_id INTEGER NOT NULL,
book_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price DECIMAL(8,2) NOT NULL CHECK (unit_price >= 0),
PRIMARY KEY (order_id, book_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (book_id) REFERENCES book (book_id)
);Read these as the design in code. Each order must belong to an existing customer (NOT NULL plus FOREIGN KEY), and a customer with orders can't be deleted (RESTRICT). Order lines have a composite primary key, so the same book can't appear twice in one order; increase the quantity instead. Lines disappear with their order (CASCADE) but block deleting a book that has been sold. Quantities must be positive and prices can't be negative.
Order of creation matters: a table must exist before another table can reference it, so customer comes before orders, and orders and book before order_line.
Step 6 of 15Practice · Spot the mistake
This CREATE TABLE statement is meant to implement the enrollment junction table. Tap the two lines that contain design mistakes.
Step 7 of 15Learn
Changing a schema safely
Designs evolve. A new requirement arrives, and the schema must change while the system holds real data. ALTER TABLE handles this:
ALTER TABLE customer ADD COLUMN phone VARCHAR(20);
ALTER TABLE book ADD CONSTRAINT book_price_ok CHECK (price >= 0);
ALTER TABLE customer DROP COLUMN city;On a live system, a few habits prevent trouble:
- Adding a NOT NULL column to a populated table fails unless you give it a DEFAULT or fill existing rows first. A common pattern is: add the column as nullable, backfill values with an UPDATE, then add NOT NULL.
- Adding a constraint fails if existing rows violate it. Find and fix the bad rows first, which is often how teams discover data quality problems they didn't know about.
- Dropping or renaming a column breaks every query and program that uses it. Change the code first, then the schema.
- Name your constraints (like book_price_ok above). Error messages then say which rule failed, and the constraint is easy to drop or change later.
Most teams keep schema changes in versioned migration files stored with the application code, so every environment, from a developer's laptop to production, gets the same changes in the same order, and the history of the design is recorded.
Step 8 of 15Practice · Code challenge · SQL
Code challenge · SQL
The tables orders and book already exist. Create the junction table order_line with:
- order_id and book_id: integers, NOT NULL, each a FOREIGN KEY to its table
- quantity: integer, NOT NULL
- a composite PRIMARY KEY (order_id, book_id), in that order
The checker inspects the columns, the primary key and the foreign keys.
The database for this exercise (tables and rows)
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, order_date TEXT NOT NULL);
CREATE TABLE book (book_id INTEGER PRIMARY KEY, title TEXT NOT NULL);- Result matches the expected table
Step 9 of 15Practice · Put in order
A bookstore must add a required country column to a customer table that already holds 50,000 rows. Order the safest steps.
Drag the items, or use the arrow buttons, to put them in order.
- Deploy the application code that always supplies country on insert
- Alter the column to NOT NULL
- Fill in country for all existing rows with an UPDATE
- Verify that no rows still have a NULL country
- Add country as a nullable column
Step 10 of 15Diagram
A safe migration for a new required column
Tap a shape with to see more.
- Add the column as nullable
Existing rows get NULL; nothing breaks.
- Deploy code that fills it
New rows now arrive with a value.
- Backfill old rows
In batches on large tables, to avoid long locks.
- Add NOT NULL
Succeeds only once no NULLs remain.
Step 11 of 15Note
Step 12 of 15Learn
Constraints that save you later
A few constraints are especially valuable for the effort they take.
- CHECK on ranges and enumerations: CHECK (rating BETWEEN 1 AND 5), CHECK (status IN ('pending', 'shipped', 'delivered', 'canceled')). Typos like "shiped" are rejected at once instead of breaking reports that count shipped orders.
- CHECK across columns: CHECK (end_date >= start_date) on a booking table makes impossible bookings impossible.
- UNIQUE on natural keys even when a surrogate key exists, so the same ISBN or email can't sneak in twice.
- Composite UNIQUE for business rules: UNIQUE (room_id, booking_date) stops double-booking a room on the same day.
- NOT NULL on foreign keys wherever participation is mandatory.
A useful mental exercise is to imagine the worst data a buggy script could insert, such as an order dated in 1900, a negative quantity, a booking that ends before it starts, or a duplicate account, and ask which constraint would stop it. Each one you add is a test that runs on every single write, forever, for free.
Step 13 of 15Practice · Match the pairs
Match each business rule to the constraint that enforces it.
Tap an answer, then tap the place where it belongs (or drag it there).
- A room cannot be booked twice for the same date
- A booking cannot end before it starts
- Every booking belongs to an existing guest
- A status must be one of a fixed set of values
Step 14 of 15Flashcards
Constraint cheat sheet
Tap a card to flip it.
Step 15 of 15Practice · Choose one
Why must the customer table be created before the orders table in the bookstore schema?
Lesson complete!