SQL CREATE TABLE: Columns, Types and Constraints
Every table you have queried was created with a CREATE TABLE statement. Designing a table means choosing its columns, their types, and the constraints that stop bad data from getting in. Constraints are your last line of defense: the application may have bugs, but the database will refuse a review with a rating of 11.
Columns and types
Each column has a name and a declared type. Standard types include INTEGER, REAL (floating point), TEXT and BLOB (binary data). Other databases add VARCHAR(n), DECIMAL, DATE, BOOLEAN and more.
SQLite is unusual: its typing is flexible. The declared type is a preference (a "type affinity"), and a column can technically hold any kind of value. typeof() reports what is actually stored, which the last query uses. Add STRICT after the closing parenthesis, in SQLite 3.37 and later, to enforce types the way other databases do.
Constraints
PRIMARY KEYidentifies each row uniquely. In SQLite, anINTEGER PRIMARY KEYcolumn is filled in automatically when you leave it out of anINSERT.NOT NULLforbids missing values.UNIQUEforbids duplicates, such as two accounts with the same email.CHECK (rating BETWEEN 1 AND 5)rejects any row for which the expression is false.DEFAULTsupplies a value when anINSERTleaves the column out. It can be an expression in parentheses, like(date('now')).REFERENCES books(id)declares a foreign key: eachbook_idmust match an existing book.
Expected output
title | reviews | avg_rating Learning SQL by Doing | 1 | 5.0 Paper Cranes | 2 | 4.5 typeof(rating) | typeof(comment) integer | null
What the example shows
The new reviews table links to books. The second review passes NULL for comment explicitly, so the default is not used: defaults apply only to columns that are left out. The join then reports the number of reviews and the average rating per book. Try changing a rating to 7 and running again: the CHECK constraint rejects the insert with an error.
Foreign keys in SQLite
For backward compatibility, SQLite does not enforce foreign keys unless you run PRAGMA foreign_keys = ON; on each connection. Most other databases enforce them always. Turn them on in every application that uses SQLite.
Changing a table later
ALTER TABLE books ADD COLUMN isbn TEXT; adds a column, and DROP TABLE IF EXISTS reviews; deletes a table with all its data. Real projects record such changes as migrations, small numbered scripts kept with the code.
Common mistakes
- Storing money as
REAL; store integer cents or use a decimal type where available. - Leaving out
NOT NULLon columns that must always have a value. - Forgetting that SQLite needs
PRAGMA foreign_keys = ONto enforceREFERENCES.
Summary
CREATE TABLE name (column type constraints, ...)defines a table.PRIMARY KEY,NOT NULL,UNIQUE,CHECK,DEFAULTandREFERENCESprotect data quality.- SQLite types are flexible unless the table is
STRICT;typeof()shows the stored type.
Quiz: CREATE TABLE and constraints