Skip to the workspace
Pebellslearn by building
Object Model  ›  Lesson

Data Types and Domains

Data Types 12 minA column's type defines its domain of allowed values, and CREATE DOMAIN names a restricted type that many columns can share.

postgresql dba / Data Types and Domains

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.