Sub topic 17
Choosing types for a schema
This chapter assumes you can run CREATE TABLE, INSERT and SELECT in psql, and that you know what a column and a constraint are. It also assumes you have read the earlier chapters on integers, numeric, floating point, text, dates and times, UUIDs, jsonb and enums. Here you combine those pieces into one schema and learn how to decide between them.
A decision procedure
Pick a type by asking questions in a fixed order. Stop at the first question that gives a clear answer.
- Is the value a fixed set of labels, a true/false flag, or a point in time? Use
enumor a lookup table,boolean, ortimestamptz. - Is it a number? If it must be exact (money, quantities, rates), use
numeric(p,s)or an integer count of minor units. If it is a measurement that tolerates tiny error (sensor readings, scientific values), usedouble precision. - Is it a whole number? Use
integerby default, andbigintif the table could pass about 2 billion rows or the value could exceed that. - Is it text? Use
text, and add aCHECKconstraint if you need a length limit. - Is it an identifier? Use a
bigintidentity column unless ids must be generated outside the database or must not be guessable. In those cases useuuid. - Is it a nested document with a shape that varies? Use
jsonb. Otherwise use plain columns.
The rest of the chapter explains the reasoning behind each answer.
Defaults that are usually right
The following table summarizes the defaults and the reason for each.
| Kind of value | Default type | Reason |
|---|---|---|
| Surrogate key | `bigint GENERATED ALWAYS AS IDENTITY` | Avoids overflow, and `ALWAYS` stops accidental manual ids |
| Money, rates | `numeric(12,2)` or similar | Exact decimal arithmetic |
| Measurements | `double precision` | Fast, 15 significant digits, rounding is acceptable |
| Names, emails, notes | `text` | No performance penalty versus `varchar(n)` |
| Flags | `boolean NOT NULL` | Removes the third state unless you need it |
| Event times | `timestamptz` | Stores an unambiguous instant |
| Calendar dates | `date` | No time-of-day confusion |
| Variable documents | `jsonb` | Indexable and queryable |
Worked example: an orders table
This table applies the defaults. Each column has a reason for its type.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_email text NOT NULL,
total numeric(12,2) NOT NULL CHECK (total >= 0),
is_paid boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now()
);idis abigintidentity. Anintegerkey holds up to 2,147,483,647 rows. Changing a key type later means rewriting the table and every foreign key that points at it, so the extra four bytes per row are cheap insurance.customer_emailistext. PostgreSQL storestextandvarchar(n)the same way, so a length limit adds no speed. If the business needs a limit, addCHECK (length(customer_email) <= 254). A check is easier to change than avarchar(n)limit in some situations and is visible as a named constraint.totalisnumeric(12,2). It holds up to 10 digits before the decimal point and 2 after. TheCHECKrejects negative totals.is_paidisNOT NULLwith a default. A nullable boolean has three states (true, false, unknown), and most flags only have two.created_atistimestamptz. It records an instant, and PostgreSQL converts it to the session time zone when you read it.
Here is why exact numbers matter for money:
SELECT
0.1::double precision + 0.2::double precision = 0.3::double precision AS float_equal,
0.1::numeric + 0.2::numeric = 0.3::numeric AS numeric_equal;float_equal is false and numeric_equal is true. Binary floating point cannot represent 0.1 exactly, so sums drift. In a ledger, that drift becomes a mismatch you cannot explain.
Trade-offs worth knowing
Integer width
smallint (2 bytes) saves space only when you have very many rows and the range is truly bounded. Alignment padding often removes the savings when a narrow column sits next to a wider one. Use smallint for things like a month number, and integer or bigint otherwise.
Money as numeric or integer cents
Both approaches are correct. numeric(12,2) reads naturally in queries and handles fractions of a currency unit if you widen the scale. Integer minor units (cents) are compact and fast, but every reader has to remember to divide by 100. Choose one convention for the whole schema. Do not use the money type. Its formatting depends on the lc_monetary setting and it handles only one currency.
text versus varchar(n) versus char(n)
Use text unless a fixed limit is part of the data's meaning. char(n) pads with spaces and is almost never what you want. Changing varchar(n) to a larger limit is cheap, but shrinking it forces a check of every row.
UUID versus bigint keys
A random UUID is 16 bytes against 8 for bigint. Random values also scatter inserts across the primary key index, which causes more page splits and cache misses on large tables. UUIDs are the better choice when clients create ids offline, when you merge data from several systems, or when ids appear in URLs and must not be guessable. Time-ordered UUIDs reduce the index scatter. Every foreign key that references the key repeats the larger size.
jsonb versus columns
Use jsonb for data whose shape varies by record or is controlled by another system, such as webhook payloads. Use real columns for anything you filter, join, sort or constrain on a regular basis. Columns give you type checking, NOT NULL, foreign keys and accurate planner statistics. A common pattern is real columns for the stable fields and one jsonb column for the rest.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL
);
INSERT INTO events (payload) VALUES ('{"type": "signup", "plan": "pro"}');
SELECT payload ->> 'plan' AS plan
FROM events
WHERE payload @> '{"type": "signup"}';
CREATE INDEX events_payload_idx ON events USING gin (payload);The @> operator tests containment, and the GIN index supports it.
Enums, domains and lookup tables
An enum is compact and sorts in declaration order, but you can add values only with ALTER TYPE ... ADD VALUE, and you cannot remove them. If the set of values changes often, or each value needs extra attributes, use a lookup table with a foreign key. A domain gives a reusable constraint:
CREATE DOMAIN positive_int AS integer CHECK (VALUE > 0);
CREATE TABLE line_items (
order_id bigint NOT NULL,
quantity positive_int NOT NULL
);Changing a domain's constraint later affects every column that uses it, which is useful for consistency and risky for large tables.
Arrays and ranges
Arrays suit short lists that you always read and write together, such as tags. If you need to join on the elements or enforce foreign keys, use a child table. Ranges such as daterange model intervals directly and support overlap checks with an exclusion constraint, which is much safer than two separate start and end columns.
Times and time zones
Use timestamptz for anything that happened or will happen at a specific moment. Despite the name, it does not store a time zone. It stores a UTC instant and displays it in the session's TimeZone setting. Use plain timestamp only for wall-clock values that have no zone, such as "the shop opens at 09:00 local time". To see an instant as local time, use AT TIME ZONE:
SELECT '2026-01-15 12:00:00+00'::timestamptz AT TIME ZONE 'America/New_York' AS new_york_local;The result is 2026-01-15 07:00:00, a timestamp without a zone.
Casting and conversion errors
Conversions are explicit with :: or CAST(). A value that cannot be parsed raises an error, which is useful because it stops bad data at the boundary.
SELECT '42'::integer + 1 AS answer,
CAST('2026-01-15' AS date) AS d;
SELECT 'abc'::integer; -- ERROR: invalid input syntax for type integer: "abc"Common mistakes
- Using
double precisionorrealfor money. - Using
timestampfor event times and then reading them from sessions with different time zones. - Using
integerkeys on a table that grows without bound. - Storing every field in one
jsonbcolumn and losing constraints and statistics. - Leaving flag columns nullable by accident, so
WHERE NOT is_paidskips rows withNULL. - Using
char(n)and being surprised by trailing spaces.
Exercise
You are designing a payments table. Columns: an internal id, the amount in a single currency with cents, whether it was refunded, the moment it was received, and a webhook body from the payment provider whose fields change between providers. Write the CREATE TABLE statement and give one sentence of justification for the type of each column.
Show answer
CREATE TABLE payments ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, amount numeric(12,2) NOT NULL CHECK (amount > 0), isrefunded boolean NOT NULL DEFAULT false, receivedat timestamptz NOT NULL DEFAULT now(), webhook jsonb NOT NULL ); The id is a bigint identity so the key cannot overflow and is not set by hand. The amount is numeric(12,2) because money needs exact decimal arithmetic. The flag is a NOT NULL boolean with a default so it has only two states. The received time is timestamptz because it is a specific instant. The webhook is jsonb because its shape varies by provider and does not need column-level constraints.
Exercise
A teammate proposes storing a room booking as two columns, start_date date and end_date date, and checking for double-booking in application code. Which PostgreSQL type would model this better, and what database feature would then enforce no overlaps?
Show answer
Use a daterange column, for example stay daterange NOT NULL. Add an exclusion constraint such as EXCLUDE USING gist (room_id WITH =, stay WITH &&) (this needs the btreegist extension for the equality on roomid). The database then rejects any two bookings for the same room whose ranges overlap, so the rule cannot be bypassed by application bugs.