PostgreSQL JSON Cheat Sheet
www.databasestar.com
JSON Example Selecting Updating
{ Update field by concatenating:
“color”: “black”, Select with key and value:
“drawers”: [ (displays a value such as "blue" with surrounding quotes) UPDATE product
{ SET attributes =
SELECT attributes || '{"width":"100cm"}'
“side”: “left”,
id, WHERE id = 1;
“height”: “30cm”
product_name,
},
attributes -> 'color' AS color_key Update field using jSONB_SET:
{
FROM product;
“side”: “left”,
UPDATE product
“height”: “40cm”
Select with key and value: SET attributes =
}
(displays a value such as "blue" without surrounding quotes) JSONB_SET(attributes, '{height}', '"75cm"')
],
WHERE id = 1;
“material”: “metal” SELECT
} id,
product_name,
Deleting
Data Types attributes ->> 'color' AS color_key
FROM product;
Delete based on filter:
JSON: regular JSON
Select an array value with key and value: DELETE FROM product
JSONB: JSON Binary. The recommended data type. WHERE attributes ->> 'color' = 'brown';
SELECT Remove attribute from field:
id,
Creating a JSON Field product_name,
attributes -> 'drawers' -> 1 AS drawer_value
UPDATE product
SET attributes = attributes - 'height'
FROM product; WHERE id = 1;
Create Table with JSONB field:
CREATE TABLE product (
Select an array value with key and value as object or as text
id INT,
product_name CHARACTER VARYING(200),
attributes JSONB SELECT
); id,
product_name,
attributes #> '{drawers, 1}' AS drawers_element,
Create Table with JSON field:
attributes #>> '{drawers, 1}' AS drawers_text
CREATE TABLE product ( FROM product;
id INT,
product_name CHARACTER VARYING(200),
attributes JSON
); Filtering
Insert JSON Data Filtering a value with key and value:
Insert statement: SELECT
id,
INSERT INTO product (id, product_name, attributes) product_name,
VALUES ( attributes
1, FROM product
'Chair', WHERE attributes ->> 'color' = 'brown';
'{"color":"brown", "material":"wood",
"height":"60cm"}'
Filtering where a key exists:
);
Insert array: SELECT
id,
INSERT INTO product (id, product_name, attributes) product_name,
VALUES ( attributes
3, FROM product
'Side Table', WHERE attributes ? 'drawers' = true;
'{"color":"brown", "material":["metal", "wood"]}'
);
Insert with JSONB_BUILD_OBJECT:
Split Data into Rows
INSERT INTO product (id, product_name, attributes) Split each element into separate rows:
VALUES (
4, SELECT
'Small Table', id,
JSONB_BUILD_OBJECT( product_name,
'color', 'black', 'material', 'plastic' JSONB_EACH(attributes)
) FROM product;
);
Get all keys:
Other functions for inserting:
TO_JSON and TO_JSONB SELECT
ARRAY_TO_JSON id,
ROW_TO_JSON product_name,
JSON_BUILD_ARRAY and JSONB_BUILD_ARRAY JSONB_OBJECT_KEYS(attributes)
JSON_OBJECT and JSONB_OBJECT FROM product;