3 Hours

11. Hybrid Schemas: Combining Relational and Document

Hybrid

Hybrid Schemas: The Best of Both Worlds

Modern applications often need both relational and document capabilities. Hybrid schemas combine structured data with flexible document storage. This module covers when and how to use hybrid schemas, and the trade-offs involved.

Hybrid schemas use relational tables for structured, well-defined data and document fields (like JSONB) for flexible, unpredictable data. This gives you the best of both worlds: the integrity of relational and the flexibility of document.

When to Use Hybrid Schemas

Use hybrid schemas when you have a mix of structured and flexible data. Common scenarios: user preferences (flexible attributes), product catalogs (varying attributes), and event logging (unstructured data).

Data TypeWhere to StoreExamplesBenefit
StructuredRelational Columnsid, email, name, created_atFast queries, data integrity
FlexibleJSONB Fieldspreferences, metadata, attributesNo schema changes needed
SQL
-- Hybrid schema: Users with metadata
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email TEXT UNIQUE NOT NULL,
  name TEXT NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  preferences JSONB DEFAULT '{}'::jsonb,
  metadata JSONB DEFAULT '{}'::jsonb
);

-- Query JSON data
SELECT id, name, preferences->>'theme' AS theme
FROM users
WHERE preferences @> '{"theme": "dark"}'::jsonb;

-- Update JSON data
UPDATE users SET preferences = jsonb_set(preferences, '{theme}', '"light"')
WHERE email = 'alice@example.com';

Knowledge Check

Ready to test your understanding of 11. Hybrid Schemas: Combining Relational and Document?

Back