SQL Practice Logo

SQLPractice Online

PostgreSQL: Arrays & JSONB: Performance

Module: Database-Specific Features

Arrays and JSONB provide better performance than normalized tables for specific use cases: (1) Arrays: 2-3x faster than junction tables (no JOIN needed), but limited queries. Use GIN index for fast containment queries (@>, &&). (2) JSONB: 2-3x faster than MySQL JSON (binary format), indexable with GIN. Avoid deep nesting (3+ levels slow). (3) GIN indexes: 10-100x faster queries, but slower updates (index must be updated). (4) Array size: Keep arrays small (< 100 items), large arrays slow. (5) JSONB size: Keep documents small (< 1MB), large documents slow. Real-world: Amazon uses arrays for product categories (2-3x faster). Stripe uses JSONB for metadata (flexible schema). GitLab uses GIN indexes (10x faster queries).

Arrays: 2-3x faster than junction tables (no JOIN), use GIN index for @>, && queries

JSONB: 2-3x faster than MySQL JSON (binary format), use GIN index for ->, @>, ? queries

GIN indexes: 10-100x faster queries, but slower updates (index must be updated)

Array size: Keep < 100 items, large arrays slow (sequential scan even with index)

JSONB size: Keep < 1MB, large documents slow (parsing overhead)

Deep nesting: Avoid 3+ levels, each level adds overhead (parsing, traversal)

Use @> for containment: Faster than multiple -> queries, leverages GIN index

Using JSON instead of JSONB: JSON is text format (slower), not indexable, use JSONB

Not creating GIN indexes: Sequential scan is slow for large tables, always create GIN index

Large arrays: > 100 items slow down queries/updates, use junction table instead

Deep JSONB nesting: 3+ levels slow, flatten structure or use normalized tables

Using arrays for complex relationships: Arrays can't query relationship attributes, use junction table