0% found this document useful (0 votes)
127 views

Postgresql Jsonb Cheatsheet en

The document provides a cheatsheet on JSONB functions in PostgreSQL. It shows examples of using JSON path queries and functions to extract and retrieve fields, subpaths and items from JSONB data stored in a database table.

Uploaded by

Nana Yaw Adeh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views

Postgresql Jsonb Cheatsheet en

The document provides a cheatsheet on JSONB functions in PostgreSQL. It shows examples of using JSON path queries and functions to extract and retrieve fields, subpaths and items from JSONB data stored in a database table.

Uploaded by

Nana Yaw Adeh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

PostgreSQL ®

JSONB Functions Cheatsheet


https://www.postgresql.org/docs/current/functions-json.html
@ftisiot

Dataset Extract Fields Jsonpath query


Extract JSON field Extract JSON field as text Extract JSON subpath Extract item from array Extract path Does JSON path return any item
create table test(id serial, json_data jsonb); select select select select
select
select
insert into test(json_data) values ( json_data -> 'id' id, json_data ->> 'id' id, json_data #> json_data jsonb_extract_path(json_data,
json_data

'{ json_data -> 'name' name json_data ->> 'name' name '{pizzas,1,additionalToppings}' -> 'phoneNumbers' -> 1 'pizzas','1','pizzaName') second_pizza_name
@? '$.pizzas[1].pizzaName == "Salami"'

"id": 778, from test; from test; as additional_toppings_2nd_pizza as second_phonenumber from test;
as pizzaName_salami
from test;
"shop": "Luigis Pizza", from test; from test;
"name": "Edward Olson",
"phoneNumbers": id | name
-----+----------------
id | name
-----+----------------
additional_toppings_2nd_pizza
------------------------------------
second_phonenumber
--------------------
second_pizza_name
-------------------

["(935)503-3765x4154","(935)12345"], 778 | "Edward Olson" 778 | Edward Olson 🍌 🌶 🍍


[" ", " ", " "] "(935)12345" "Margherita"
pizzaname_salami
------------------
"address": "Unit 9398 Box 2056\nDPO AP 24022", t

"image": null,
"pizzas": [
{

🥓 🌶
"pizzaName": "Salami",
"additionalToppings": [" ", " "] Contains query Does JSON path return any item Return JSON path itemsany item
}, select select
{ JSON A contains JSON B JSON A contains Item B JSON A contains any item in B JSON A contains all items in B in B jsonb_path_exists(json_data, jsonb_path_query(json_data,

🍌 🌶 🍍
"pizzaName": "Margherita", select select '$.pizzas[*].pizzaName == "Salami"') '$.pizzas[*] ? (@.pizzaName == "Salami")')
select select
"additionalToppings": [" ", " ", " "] json_data json_data json_data as is_there_salami_pizza as is_there_salami_pizza
json_data ? 'shop'
} @> '{"id": 778}'::jsonb as contains_shop
?| ARRAY['shop','cookies'] ?& ARRAY['shop','cookies'] from test; from test;
as contains_shop_or_cookies as contains_shop_and_cookies
] as contains_id from test; from test; from test;
}'); from test; salami_pizza is_there_salami_pizza
-------------- -----------------------------------------------------------
contains_id contains_shop
---------------
contains_shop_or_cookies
--------------------------
contains_shop_and_cookies
--------------------------
t
{"pizzaName": "Salami", "additionalToppings": [" 🥓", "🌶"]}
------------ t f
t t

Create JSON Objects Parse Arrays Types


Convert item/row to JSON Create heterogeneously-typed JSON array Build JSON object from list of items Convert array elements to JSON rows Convert array elements to text rows Return array length Get item type
select select select select p.* select p.* select select
to_jsonb(
row(33,
jsonb_build_array(1,4,' 🍌', 'pizza'); jsonb_build_object(
'name', 'francesco',
from test from test jsonb_array_length( jsonb_typeof(json_data->'id') type_id,
cross join lateral jsonb_array_elements( cross join lateral jsonb_array_elements_text( json_data -> jsonb_typeof(json_data->'name') type_name
'the pizza is in the oven'::text)); 'pizzas', ARRAY['Margherita','Diavola']);
json_data -> 'phoneNumbers') p; json_data -> 'phoneNumbers') p; 'phoneNumbers') from
from test; test;
🍌
to_jsonb jsonb_build_array jsonb_build_object
---------------------------------------------- ---------------------- -------------------------------------------------------------
{"f1": 33, "f2": "the pizza is in the oven"} [1, 4, " ", "pizza"] {"name" : "francesco", "pizzas" : ["Margherita","Diavola"]}
value value jsonb_array_length
---------------------- -------------------- type_id | type_name
-------------------- ---------+-----------
"(935)503-3765x4154" (935)503-3765x4154
2 number | string
"(935)12345" (935)12345

Convert array to JSON array Build JSON object from text array Build JSON object from key and value arrays
select array_to_json( select select
ARRAY[' 🍌', '🌶', '🍍']); jsonb_object( jsonb_object(

Parse Keys
'{{name, francesco}, {pizza, "Margherita"}}'); '{name, pizza}',
'{francesco, Margherita}'); Prettify
Return key/values as JSON rows Return key/values as text rows Extract all keys Prettify JSON output
array_to_json jsonb_object jsonb_object
------------------------------------------------
🍌 🌶 🍍
---------------
[" "," "," "] {"name" : "francesco", "pizza" : "Margherita"}
------------------------------------------------
{"name" : "francesco", "pizza" : "Margherita"}

select p.* select p.* select select


from test from test jsonb_object_keys(json_data) jsonb_pretty(json_data->'pizzas')
cross join lateral jsonb_each(json_data) p; cross join lateral jsonb_each_text(json_data) p; from test; from test;

Tabulate Concat JSON A and JSON B


key | value
key | value
jsonb_object_keys
[
jsonb_pretty
------------------------------------
+
--------------+---------------------------------- { +
select --------------+----------------------------------- -------------------
Extract to record based on type Extract to recordset based on type
id | 778 "pizzaName": "Salami", +
id | 778
id
json_data name | Edward Olson "additionalToppings": [ +
name | "Edward Olson"
shop | Luigis Pizza name
🥓", +
🥓", "🌶"]}, ...]
"
"🌶"
shop | "Luigis Pizza"

create type pizzaOrder create type pizza as ("pizzaName" text,


|| '{"note":"leave outside"}' pizzas 🥓 🌶
| [{"pizzaName": "Salami", "additionalToppings": [" ", " "]}, ...]
pizzas
address
| [{"pizzaName": "Salami", "additionalToppings": ["
| Unit 9398 Box 2056
shop
pizzas
]
+
+
address | "Unit 9398 Box 2056\nDPO AP 24022"
as add_note | DPO AP 24022 address
}, +
as (id int, name text, address text); "additionalToppings" text[]); phoneNumbers | ["(935)503-3765x4154", "(935)12345"]
phoneNumbers
from test; phoneNumbers | ["(935)503-3765x4154", "(935)12345"] ... +
select p.* select p.* from test ]

from test cross join lateral cross join lateral


jsonb_populate_record( jsonb_populate_recordset( add_note
-------------------------------
null::pizzaOrder, json_data) p; null::pizza, json_data -> 'pizzas') p; {"id": 778,
"name": "Edward Olson",
"note": "leave outside",
"shop": "Luigis Pizza",...}

id | name | address
-----+--------------+--------------------
778 | Edward Olson | Unit 9398 Box 2056+
pizzaName | additionalToppings
------------+--------------------
Salami | { , }🥓🌶 Edit
| | DPO AP 24022 🍌🌶🍍
Margherita | { , , }

Remove items in A Remove specified path Remove item # from array Add/modify items Remove nulls Insert items
select select select select select select
Extract to record declaring columns Extract to recordset declaring columns json_data json_data (json_data -> 'phoneNumbers') - 1 jsonb_set(json_data -> 'pizzas', jsonb_strip_nulls(json_data) no_nulls jsonb_insert(json_data,
- ARRAY['pizzas','id'] #- '{pizzas,1,additionalToppings}' as no_first_phone_number '{0,"pizzaName"}', from test; '{"phoneNumbers",0}',
select p.* from test select p.* from test
as no_pizzas_and_id as no_2nd_pizza_additionalToppings from test; to_jsonb('4 Stagioni'::text), false) to_jsonb('12345'::text), false)
cross join lateral cross join lateral
from test; from test; as change_first_pizza_name as add_first_phone_number
jsonb_to_record(json_data) jsonb_to_recordset(json_data -> 'pizzas')
as p(id int, "phoneNumbers" text[]); as p("pizzaName" text, from test; from test;
no_pizzas_and_id no_2nd_pizza_additionaltoppings
"additionalToppings" text[]); no_first_phone_number
---------------------------------- -------------------------------------------
------------------------
{"name": "Edward Olson", {"id": 778, change_first_pizza_name The JSON document doesn’t contain the image add_first_phone_number
"name": "Edward Olson", ["(935)503-3765x4154"] field which was null --------------------------------------------------------------------
"shop": "Luigis Pizza", ------------------------------------------------------------------------------
id | phoneNumbers pizzaName | additionalToppings "address": "Unit 9398 Box 2056\nDPO AP 24022", "shop": "Luigis Pizza", [{"pizzaName": "4 Stagioni", "additionalToppings": [" 🥓", "🌶"]}, {"id": 778, "name": "Edward Olson", "shop": "Luigis Pizza",...,

-----+--------------------------------- ------------+--------------------
Salami 🥓,🌶}
| {
"phoneNumbers": ["(935)503-3765x4154", "(935)12345"]} "pizzas": [
{"pizzaName": "Salami", additionalToppings": [" 🥓", "🌶"]}, {"pizzaName": "Margherita", "additionalToppings": [" 🍌", "🌶", "🍍"]}] "phoneNumbers": ["12345", "(935)503-3765x4154", "(935)12345"]}

Margherita | {🍌,🌶,🍍}
778 | {(935)503-3765x4154,(935)12345}
{pizzaName": "Margherita"}], ...}

You might also like