JSON Queries PostgreSQL Operators
Query and index JSONB columns with PostgreSQL operators for flexible schema storage.
Code
-- postgresql: uses PostgreSQL JSON operators
-- Query nested JSON
SELECT id, data->>'name' AS name, data->'address'->>'city' AS city
FROM orders
WHERE data->>'status' = 'shipped'
AND data->'items' @> '[{"sku": "ABC"}]';
-- Create GIN index for fast JSON queries
CREATE INDEX idx_orders_data ON orders USING GIN (data);
-- Update nested field
UPDATE orders SET data = jsonb_set(data, '{status}', '"delivered"') WHERE id = 42;How the snippet works
Several statements share this file — SELECT / UPDATE / CREATE, with orders among the objects involved.
Mechanically, the statements are built from: a WHERE clause that picks out the rows one statement touches.
Applying it
Point it at the orders table.
Statements that matter
SELECT id, data->>'name' AS name, data->'address'->>'city' AS city
FROM orders
WHERE data->>'status' = 'shipped'
AND data->'items' @> '[{"sku": "ABC"}]';
UPDATE orders SET data = jsonb_set(data, '{status}', '"delivered"') WHERE id = 42;
CREATE INDEX idx_orders_data ON orders USING GIN (data);
Interactive Tools for This Topic
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
FAQ
- What relations does the SQL touch?
- `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.