Creating tables and constraints
Data is only as good as its structure. CREATE TABLE defines a table's columns, their types, and constraints: rules the database enforces so bad data can't get in.
Creating a table
Common data types
| Concept | PostgreSQL | MySQL | SQLite |
|---|---|---|---|
| Whole number | INTEGER, BIGINT |
INT, BIGINT |
INTEGER |
| Decimal (money) | NUMERIC(10,2) |
DECIMAL(10,2) |
NUMERIC / REAL |
| Text | TEXT, VARCHAR(n) |
VARCHAR(n), TEXT |
TEXT |
| True/false | BOOLEAN |
BOOLEAN (tinyint) |
INTEGER 0/1 |
| Date & time | DATE, TIMESTAMPTZ |
DATE, DATETIME |
TEXT (ISO dates) |
| JSON | JSONB |
JSON |
TEXT + JSON functions |
Never store money as a float in a real system. Floats can't represent
0.1exactly. UseNUMERIC/DECIMAL, or store integer cents.
Constraints
| Constraint | Guarantees |
|---|---|
PRIMARY KEY |
Unique, non-null identifier for each row |
NOT NULL |
A value must be provided |
UNIQUE |
No two rows share this value |
CHECK (...) |
A custom rule is always true |
DEFAULT |
Value used when none is given |
FOREIGN KEY / REFERENCES |
Value must exist in another table |
Watch the database reject bad data. Run each block and read the error:
Foreign keys
A foreign key links a column to another table's primary key, so you can't create an enrollment for a course that doesn't exist.
Now try inserting (1, 99) and see the foreign key error. ON DELETE CASCADE means deleting a course automatically deletes its enrollments.
Changing and removing tables
DROP TABLE courses; -- deletes the table and all its data
DROP TABLE IF EXISTS courses; -- no error if it doesn't existIn real projects, schema changes are written as migrations: versioned SQL files (managed by tools like Flyway, Prisma, Alembic or Rails migrations) so every environment's database stays in sync.
Practice
Design a reviews table: each review belongs to a customer and a product, has a rating that must be 1–5, optional comment text, and a customer can review a product only once. Insert a couple of reviews and join them to show product names.
1.Which constraint stops two users registering with the same email?
2.What does a FOREIGN KEY protect against?