CREATE TABLE example
CREATE TABLE tasks_demo (
id INTEGER PRIMARY KEY,
title VARCHAR(120) NOT NULL,
priority INTEGER NOT NULL DEFAULT 1,
completed INTEGER NOT NULL DEFAULT 0,
CHECK (priority BETWEEN 1 AND 3)
);INSERT INTO tasks_demo (id, title, priority)
VALUES (1, 'Review orders', 2),
(2, 'Update inventory', 3);
SELECT id, title, priority, completed
FROM tasks_demo
ORDER BY id;The insert does not provide completed, so the table uses its default value, 0.
Check the result with small data
First we define the columns and constraints, then we insert a valid row.
CREATE TABLE demo_schedule (
id INTEGER PRIMARY KEY,
subject TEXT NOT NULL
);
INSERT INTO demo_schedule VALUES (1,'Review SQL');
SELECT id, subject FROM demo_schedule;| id | subject |
|---|---|
| 1 | Review SQL |
CREATE TABLE creates the structure; records only appear when we insert them. A NOT NULL definition requires a subject in every row.
Check your understanding: Why would a row that supplied only id not be valid?
Show answer
Because subject is declared NOT NULL: a row with only id would leave subject as NULL and the constraint would reject it.
Common mix-ups with CREATE TABLE
Creating columns with no rules
A table that accepts any value pushes every check onto the application. If several applications write to the same database, the rules may be applied inconsistently.
Declare the real invariants in the database: keys, nullability, uniqueness, relationships and valid ranges. Do not add arbitrary constraints that the business does not need.
Designing a table for the data you will really store
Before writing the columns, describe what one row represents. In an order lines table, a row is one product within an order, so the order id alone cannot tell the lines apart. Choosing a key that matches that unit saves you from discovering duplicates after data has already been stored.
Keep three decisions separate: the type describes the domain, NOT NULL requires a value to be present and a constraint checks a rule. A required price may also need CHECK (price >= 0). The price constraint does not replace NOT NULL: a comparison with an unknown value may not reject the row. Nor does a foreign key force the column to be filled in if it still accepts nulls.
Test the design with a valid row and with attempts at a repeated id, a missing value and a value outside the domain. Run those tests on a test database. If an application and an import both write to the same table, both must run into the same rules. In SQLite, declaring a type does not give you all the type guarantees of PostgreSQL; STRICT tables and explicit constraints call for an extra decision.
Technical questions: SQLite: CREATE TABLE and constraints (opens in a new tab).