Introduction

Postgres architecture

Client (App / pgAdmin)
        ↓
PostgreSQL Server
 ├── Postmaster (main process)
 ├── Backend process (per connection)
 ├── Shared Buffers (cache)
 ├── WAL (Write Ahead Log)
 └── Background workers

JSON bs JSONB

JSON JSONB
Stored as text Stored as binary
Slow to query Fast
No index Can be indexed
Rarely used Use this always

Example create & insert:

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email TEXT,
  profile JSONB
);
INSERT INTO users (email, profile)
VALUES (
  '[email protected]',
  '{"age":22,"country":"MY","skills":["Java","Spring"]}'
);

Example select:

// Get the value
SELECT profile->>'country' FROM users;
// ->  returns JSON
// ->> returns TEXT

// JSON containment
SELECT *
FROM users
WHERE profile @> '{"country":"MY"}';

// Use in filter
SELECT *
FROM users
WHERE profile->>'country' = 'MY';

// Array contains
SELECT *
FROM users
WHERE profile->'skills' ? 'Java';

WAL (Write-Ahead Logging)

Before data changes:

  1. Write to WAL