Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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.

The shortcut

For each column ask two questions: "Must it be exact?" and "What is the biggest honest value?" Exact → numeric or an integer type. Then pick the smallest type that fits the biggest value with room to grow.

Typing the rentals tableStep 1 of 4
  1. rental_id

    Exact, and could pass two billion over the years: bigint.

The trap is timestamp without time zone for real events. It stores a wall-clock reading with no zone, so two cities' "10:00" look identical though they are hours apart.

Drills

Answer fast — trust the rule.

quick drill

Which type should hold a rental's fare?

quick drill

What does varchar(50) give you over text in PostgreSQL?

quick drill

What is a PostgreSQL domain?

quick drill

A column records when a bike was unlocked, for members in several time zones. Which type fits?

Remember

  • Pick the narrowest type that holds every real value exactly.
  • Must it be exact? What is the biggest honest value? Then choose.
  • Use domains for rules shared by many columns; use timestamptz for real events.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainType a table and defend it

Choose types for a payments table with payment_id, rental_id, amount, paid_at and card_country, and explain each choice, including why you avoided at least one tempting wrong type.