Creating tables and data types
Overview
So far you’ve used tables someone else designed. Now you’ll create your own. Designing a table means deciding three things for every column: its name, its data type, and the rules its values must follow. This lesson covers names, types and defaults; the next covers rules (constraints) in depth.
CREATE TABLE
Bean & Leaf wants customers to review products. Here’s a first version of a reviews table:
CREATE TABLE reviews (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
product_id integer NOT NULL REFERENCES products (id),
customer_id integer NOT NULL REFERENCES customers (id),
rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 5),
title text NOT NULL,
body text,
created_at timestamptz NOT NULL DEFAULT now()
);CREATE TABLEEach line inside the brackets defines one column: name, type, then optional constraints and a default. Columns are separated by commas.
Naming conventions that will save you trouble:
- lower_case_with_underscores for tables and columns. Unquoted names are folded to lower case in PostgreSQL, so
CustomerIDsilently becomescustomerid; names with capitals need double quotes forever after. - Plural table names (
reviews,orders) or singular — either works, but be consistent. - Foreign keys named after the table they point to:
product_id,customer_id. - Avoid reserved words like
order,userorgroupas names.
Choosing data types
The type is a rule and a promise: the database refuses values that don’t fit, and everyone reading the table knows what to expect. Some practical advice:
- Text: use
text. In PostgreSQL,varchar(n)is the same type with a length check, and has no speed advantage. Usevarchar(n)only when the limit is a genuine business rule (a two-letter country code, say). Avoidchar(n), which pads values with spaces. - Money:
numeric(precision, scale)— exact. Neverrealordouble precision(see Numbers and math). - Moments in time:
timestamptz— when something happened. Usedatefor calendar days (birthdays, signup dates) and plaintimestamponly for “wall-clock” times with no time zone. - Yes/no:
boolean, not'Y'/'N'text or 0/1 integers. - Counts and quantities:
integer;bigintwhen values could exceed about 2 billion (row ids in huge tables, bytes, money in cents).
Try putting a bad value into the new table and the type steps in before any constraint does:
INSERT INTO reviews (product_id, customer_id, rating, title)
VALUES (1, 1, 'five', 'Lovely');ERROR: invalid input syntax for type smallint: "five"
LINE 2: VALUES (1, 1, 'five', 'Lovely');
^Identity columns and generated ids
GENERATED ALWAYS AS IDENTITY makes PostgreSQL number the rows 1, 2, 3… automatically. ALWAYS means you can’t insert your own value by accident (you’d need OVERRIDING SYSTEM VALUE); GENERATED BY DEFAULT AS IDENTITY, used by the Bean & Leaf tables, lets you supply an id when you need to, such as when loading data from another system.
INSERT INTO reviews (product_id, customer_id, rating, title, body)
VALUES (1, 1, 5, 'Bright and floral', 'My favourite morning coffee.'),
(9, 2, 4, 'Consistent grind', NULL)
RETURNING id, product_id, rating, title; id | product_id | rating | title
----+------------+--------+-------------------
1 | 1 | 5 | Bright and floral
2 | 9 | 4 | Consistent grind
(2 rows)
INSERT 0 2You’ll still see the older serial type in tutorials and existing databases. It does the same job, but identity columns are the SQL-standard way and avoid some permission and copying quirks — prefer them for new tables.
UUIDs are the main alternative: 128-bit ids like 0193a8e4-7c5d-7b9e-9f43-3a0c2d1e8b6f, generated anywhere without asking the database for the next number. They suit distributed systems and ids that appear in URLs (they don’t reveal how many orders you have). Use the uuid type with DEFAULT gen_random_uuid(), or, since PostgreSQL 18, DEFAULT uuidv7(), which produces time-ordered UUIDs that index much more efficiently. For most applications, integer identities are simpler and smaller.
Defaults
DEFAULT gives a value to use when an INSERT doesn’t mention the column. It can be a constant (DEFAULT 0, DEFAULT true, DEFAULT 'pending') or an expression evaluated at insert time — DEFAULT now() records when the row was created, which is why the reviews above got a created_at without being given one:
SELECT id, title, created_at IS NOT NULL AS has_timestamp
FROM reviews
ORDER BY id; id | title | has_timestamp
----+-------------------+---------------
1 | Bright and floral | t
2 | Consistent grind | t
(2 rows)(The actual timestamps are whatever time you ran the insert, so they’re not shown here.)
Generated columns
A generated column is calculated from other columns in the same row, so it can never be out of date. A line-total column on an order-lines table, for example:
CREATE TABLE quote_lines (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
product_id integer NOT NULL REFERENCES products (id),
quantity integer NOT NULL,
unit_price numeric(10,2) NOT NULL,
line_total numeric(10,2) GENERATED ALWAYS AS (quantity * unit_price) STORED
);
INSERT INTO quote_lines (product_id, quantity, unit_price)
VALUES (5, 3, 9.50), (10, 1, 59.90)
RETURNING *;CREATE TABLE
id | product_id | quantity | unit_price | line_total
----+------------+----------+------------+------------
1 | 5 | 3 | 9.50 | 28.50
2 | 10 | 1 | 59.90 | 59.90
(2 rows)
INSERT 0 2You can’t write to a generated column directly; it follows its inputs. STORED computes the value on write and keeps it on disk. Since PostgreSQL 18 you can also write VIRTUAL (now the default when neither is given), which computes it each time it’s read and uses no space.
Inspecting a table
In psql, \d tablename shows a table’s structure — columns, types, defaults, constraints and indexes:
\d quote_lines Table "public.quote_lines"
Column | Type | Collation | Nullable | Default
------------+---------------+-----------+----------+---------------------------------------------------------------
id | integer | | not null | generated always as identity
product_id | integer | | not null |
quantity | integer | | not null |
unit_price | numeric(10,2) | | not null |
line_total | numeric(10,2) | | | generated always as ((quantity::numeric * unit_price)) stored
Indexes:
"quote_lines_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"quote_lines_product_id_fkey" FOREIGN KEY (product_id) REFERENCES products(id)Any client can get the same information with SQL from the standard information_schema views:
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'reviews'
ORDER BY ordinal_position; column_name | data_type | is_nullable | column_default
-------------+--------------------------+-------------+----------------
id | integer | NO |
product_id | integer | NO |
customer_id | integer | NO |
rating | smallint | NO |
title | text | NO |
body | text | YES |
created_at | timestamp with time zone | NO | now()
(7 rows)Copying and dropping tables
CREATE TABLE … AS creates a table from a query’s result — handy for snapshots and experiments (it copies data and column types, but not constraints, defaults or indexes):
CREATE TABLE tea_snapshot AS
SELECT id, name, price FROM products WHERE category_id = 2;
SELECT * FROM tea_snapshot ORDER BY id;SELECT 4
id | name | price
----+------------------------+-------
4 | Darjeeling First Flush | 18.00
5 | Assam Breakfast | 9.50
6 | Jasmine Green | 12.75
7 | Chamomile Calm | 8.00
(4 rows)DROP TABLE removes a table and all its data, permanently. IF EXISTS avoids an error if it isn’t there:
DROP TABLE IF EXISTS tea_snapshot;
DROP TABLE IF EXISTS tea_snapshot;DROP TABLE
NOTICE: table "tea_snapshot" does not exist, skipping
DROP TABLEThe second drop found nothing to do and issued a notice instead of an error. PostgreSQL won’t drop a table that other tables reference with foreign keys unless you add CASCADE — which also drops those foreign keys — so try DROP TABLE products; and read the message rather than reaching for CASCADE.
Tip: keep the
CREATE TABLEstatements for your database in a file under version control, like theshop.sqlyou downloaded. Then anyone can recreate the structure, and you can see how it changed over time — the subject of Changing table structure.
A table for suppliers
Bean & Leaf wants to track its suppliers. Create a table suppliers with: id — an integer identity primary key (GENERATED ALWAYS AS IDENTITY); name — text, required; country — text; email — text; active — boolean, required, defaulting to true; and since — a date, required, defaulting to '2026-12-04'. Insert two suppliers giving only name, country and email: Highland Estates (India, sales@highland.example) and Kyoto Teaworks (Japan, no email). Then mark Kyoto Teaworks as inactive with an UPDATE, and finally select every column, ordered by id.
CREATE TABLE suppliers (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY
-- the other five columns
);CREATE TABLE suppliers (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
country text,
email text,
active boolean NOT NULL DEFAULT true,
since date NOT NULL DEFAULT '2026-12-04'
);
INSERT INTO suppliers (name, country, email)
VALUES ('Highland Estates', 'India', 'sales@highland.example'),
('Kyoto Teaworks', 'Japan', NULL);
UPDATE suppliers SET active = false WHERE name = 'Kyoto Teaworks';
SELECT * FROM suppliers ORDER BY id;Summary
- CREATE TABLE name (column type constraints, …) defines a table; use lower_case_with_underscores names.
- Choose types by meaning: integer/bigint for counts and ids, numeric for money, text for strings, date or timestamptz for time, boolean for yes/no.
- id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY gives auto-numbered ids; uuid keys suit distributed systems, and uuidv7() makes them time-ordered.
- DEFAULT supplies a value when none is given; generated columns are computed from other columns.
- CREATE TABLE … AS copies a query's result into a new table; DROP TABLE removes a table and its data for good.