Data Types and Domains
Pedal stored rental prices as real, and the monthly revenue report came out as 18204.699999. Accountants noticed. The type you give a column decides what can be stored, how it compares and sorts, and how much space it takes, so choosing it is a design decision, not a formality.
The rule
Pick the narrowest type that holds every real value exactly.
In relational terms, a column's set of allowed values is its domain. In PostgreSQL the domain comes first from the data type, and you can narrow it further.
The types a DBA meets daily:
| Need | Type | Note |
|---|---|---|
| Ids and counts | integer, bigint |
Prefer bigint for ids that may grow |
| Money and exact decimals | numeric(10,2) |
Exact; never real for money |
| Measurements | double precision |
Fast, approximate |
| Text | text, varchar(n) |
Same speed; varchar(n) only adds a length limit |
| Yes or no | boolean |
|
| Moments in time | timestamptz |
Stores an absolute instant |
| Documents | jsonb |
Indexable JSON |
| Identifiers from outside | uuid |
PostgreSQL also lets you name a reusable restricted type with CREATE DOMAIN:
CREATE DOMAIN price_inr AS numeric(8,2)
CHECK (VALUE >= 0);
CREATE TABLE tariffs (
city text PRIMARY KEY,
per_hour price_inr NOT NULL,
day_cap price_inr NOT NULL
);Both columns now share one definition of "a valid price". Change the rule once and every column using the domain follows.