TechLead
Lesson 5 of 10
5 min read
PostgreSQL

Data Types & JSONB

Use Postgres types effectively, including JSONB for flexible data

Common Data Types

TEXT, VARCHAR(n)     -- strings
INTEGER, BIGINT      -- whole numbers
NUMERIC(10,2)        -- exact decimals
BOOLEAN              -- true/false
TIMESTAMP, DATE      -- time
UUID                 -- unique identifiers
JSONB                -- structured JSON

JSON vs JSONB

JSONB stores JSON in a binary format, enabling indexing and faster queries. Prefer JSONB for most use cases.

CREATE TABLE events (
  id SERIAL PRIMARY KEY,
  payload JSONB NOT NULL
);

SELECT payload->>'type' AS type
FROM events
WHERE payload->'meta'->>'source' = 'web';

Index JSONB

CREATE INDEX events_payload_gin
ON events USING GIN (payload);

GIN indexes make JSONB queries much faster.

Continue Learning