JSON Queries PostgreSQL Operators

Query and index JSONB columns with PostgreSQL operators for flexible schema storage.

SqlData Fetching

Code

sqlsnippet
12 lines
-- 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

FAQ

What relations does the SQL touch?
`orders` — referenced directly, no join needed.