You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Choosing the right data type for each column is one of the most important decisions when designing a PostgreSQL schema. Using the correct type improves storage efficiency, query performance, and data integrity.
| Type | Storage | Range / Notes |
|---|---|---|
| smallint | 2 bytes | -32,768 to 32,767 |
| integer | 4 bytes | -2,147,483,648 to 2,147,483,647 |
| bigint | 8 bytes | ±9.2 × 10^18 |
| numeric(p,s) | Variable | Exact arbitrary-precision decimal |
| real | 4 bytes | 6 decimal digits precision |
| double precision | 8 bytes | 15 decimal digits precision |
| serial / bigserial | 4 / 8 bytes | Auto-incrementing integers |
Use numeric for money and other values where floating-point rounding is unacceptable.
| Type | Description |
|---|---|
| char(n) | Fixed-length, padded with spaces |
| varchar(n) | Variable-length with a maximum |
| text | Unlimited variable-length string |
In PostgreSQL text and varchar without a limit have identical performance. Prefer text unless you genuinely need to enforce a maximum length at the database level.
CREATE TABLE feature_flags (
name text NOT NULL,
enabled boolean NOT NULL DEFAULT false
);
PostgreSQL accepts true/false, yes/no, on/off, and 1/0 as boolean literals.
| Type | Description |
|---|---|
| date | Calendar date (year, month, day) |
| time | Time of day (no timezone) |
| timestamp | Date and time (no timezone) |
| timestamptz | Date and time with timezone (recommended) |
| interval | A span of time |
Always prefer timestamptz over timestamp for storing moments in time so that PostgreSQL correctly converts between timezones.
PostgreSQL extends the SQL standard with types not found in most other databases:
-- Using uuid and jsonb
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
profile jsonb,
tags text[]
);
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.