Reading a Table Definition: Types, Defaults and Constraints
Before you query an unfamiliar table, it helps to read how it was created. A CREATE TABLE statement tells you what each column holds and which rules apply. This page reads one line by line.
The example
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers(id),
status TEXT NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'paid', 'shipped')),
total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
note TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (customer_id, created_at)
);
Line by line
**id INTEGER PRIMARY KEY.** A whole number that identifies each order. In SQLite, the database fills it in automatically when you insert without an id.
**customer_id INTEGER NOT NULL REFERENCES customers(id).** Each order must belong to a customer (NOT NULL), and the value must match an existing customer's id (a foreign key).
**status TEXT NOT NULL DEFAULT 'new' CHECK (...).** Text that must be present. If you do not supply it, it becomes 'new'. The CHECK allows only three values.
**total_cents INTEGER NOT NULL CHECK (total_cents >= 0).** Money stored as whole cents avoids rounding problems with decimals. It cannot be negative.
**note TEXT.** No rules at all: it may be empty (NULL). Columns without NOT NULL are optional.
**created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP.** Filled in automatically with the time of the insert.
**UNIQUE (customer_id, created_at).** A table-level rule: the same customer cannot have two orders at exactly the same moment.
What the definition tells you about queries
| You learn | So you know |
|---|---|
customer_id is a foreign key | You can JOIN orders to customers on it |
status has fixed values | You can filter on exactly these three |
note may be NULL | Use IS NULL to find orders without a note |
| Money is in cents | Divide by 100 to show amounts |
created_at has a default | You do not need to send it on insert |
How to see a table's definition
- SQLite shell:
.schema orders - PostgreSQL psql:
\d orders - MySQL:
SHOW CREATE TABLE orders;
Each shows the columns, types and rules, though the formatting differs.
Type names differ between databases
The same idea can have different type names. Whole numbers may be INTEGER, INT or BIGINT; text may be TEXT or VARCHAR(255); timestamps may be TIMESTAMP, DATETIME or text in SQLite. When you read a definition from another database, look up its types rather than assuming. Our guide to SQL data types when you are just starting covers the common ones.
Practise
Open a sample database, such as one from our list of sample databases, show the definition of its largest table, and write one sentence per column saying what it holds and which rules apply. It is a quick way to understand any database you inherit.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.