JSONB Query and Indexing Patterns
Query, filter, and index JSONB columns in PostgreSQL for flexible document-style data storage.
-- Create table with JSONB column
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
attrs JSONB NOT NULL DEFAULT '{}'
);
-- GIN index for containment queries
CREATE INDEX idx_product_attrs ON products USING GIN (attrs);
-- Query: find products with specific attributes
SELECT * FROM products
WHERE attrs @> '{"color": "red", "size": "L"}';
-- Query nested values
SELECT
name,
attrs->>'color' AS color,
(attrs->'dimensions'->>'weight')::numeric AS weight
FROM products
WHERE attrs ? 'color'
AND (attrs->'dimensions'->>'weight')::numeric < 5.0;
-- Update nested JSONB
UPDATE products
SET attrs = jsonb_set(attrs, '{dimensions,weight}', '3.5')
WHERE id = 1;Use Cases
- Flexible metadata storage
- Feature flags
- User preferences
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
JSON Aggregation and Querying
Aggregate related rows into JSON arrays and query JSONB columns with PostgreSQL native JSON operators.
Row-Level Security Policies
Enforce data access rules at the database level with PostgreSQL Row-Level Security policies.
Table Partitioning by Range
Partition large tables by date range for faster queries and easier data lifecycle management.
Deferred Foreign Key Constraints
Defer constraint checking to transaction commit for circular references and batch operations.