Creating tables
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Two kinds of SQL command
SQL has two halves:
- DDL (Data Definition Language) changes the structure — the tables themselves.
- DML (Data Manipulation Language) changes the data inside the tables. Everything so far (
SELECT) is DML.
CREATE TABLE is the main DDL command. It lists each column with a data type and marks the primary key:
CREATE TABLE customer (
id INTEGER PRIMARY KEY,
name VARCHAR(20),
city VARCHAR(15)
);
Data types and foreign keys
Common data types:
INTEGER— whole numbersVARCHAR(n)/CHAR(n)— text, up to / exactlyncharactersDECIMAL(p, s)— a number withsdecimal placesDATE,BOOLEAN
To link to another table, add a FOREIGN KEY:
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER,
FOREIGN KEY (customer_id) REFERENCES customer(id)
);
The checker reads back your table's structure to see which columns you created.
Create a table called teacher with three columns: id (INTEGER, the primary key), name (VARCHAR(20)), and subject (VARCHAR(15)).
Click Run to see the output here.