Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SQL
SQL
0/12 completed
Beginner
What is a database?SELECT: reading dataFiltering with WHERESorting and limiting results
Intermediate
Aggregates and GROUP BYJOINs: combining tablesINSERT, UPDATE and DELETECreating tables and constraints
Advanced
Subqueries and CTEsWindow functions
Pro
Indexes and transactionsDatabase design and normalization
Tracks / SQL / Intermediate

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

SQL · editable

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.1 exactly. Use NUMERIC/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:

SQL · editable
SQL · editable

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.

SQL · editable

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

SQL · editable
sql
DROP TABLE courses;            -- deletes the table and all its data
DROP TABLE IF EXISTS courses;  -- no error if it doesn't exist

In 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.

SQL · editable
✎ Check your understanding

1.Which constraint stops two users registering with the same email?

2.What does a FOREIGN KEY protect against?

← INSERT, UPDATE and DELETE