DEV Community

Francesco Tisiot
Francesco Tisiot

Posted on • Edited on • Originally published at aiven.io

PostgreSQL® JSONB Cheatsheet: Complete & Fast Lookup Guide

How do I extract a JSON item? What about tabulating the content? Can I build a set of rows from an array?

If you need a FREE PostgreSQL database?
🦀 Check Aiven's FREE plans! 🦀
⚡️ Need to optimize your SQL query with AI? ⚡️
🐧 Check Aiven AI Database Optimizer! Powered by EverSQL 🐧

Dealing with JSON datasets in PostgreSQL® is becoming more and more common, and we can see the mix PostgreSQL + JSON appearing frequently in StackOverflow. Knowing all the PostgreSQL JSON functions and operators by heart might make you famous at a PostgreSQL trivia night, but is not an essential skill to have.

We're therefore happy to release the PostgreSQL® JSONB Cheatsheet, a complete and fast lookup guide to all the PostgreSQL JSONB functions and operators. The cheatsheet provides a set of consistent examples of all the most common JSONB functions and operators.

Note: PostgreSQL actually has two JSON datatypes, json and jsonb. The first validates that the content is in JSON format and stores it as a string, the second is a binary representation optimised for faster processing and better indexing. You can read more on StackOverflow. If you need the JSON functions instead, they're really similar but without the b ending.

Image of the cheatsheet

The image above is only for display purposes, download the high resolution copy with full copy/paste features.

Get a PostgreSQL database

The operators and functions will work with any PostgreSQL database, all the docs have been checked from 9.5+, include both the JSON and JSONB functions.

In this walkthrough, we're going to use an Aiven for PostgreSQL database: we can create one, using the $300 and 30 days trial period, by accessing the Aiven Console, clicking on Create Service and then filling in the following details:

  • Service type: the choice is PostgreSQL®, any version is ok. We can select the newly released Version 15.
  • Cloud provider and region: we can deploy our PostgreSQL wherever we want. Feel free to select your favourite cloud provider and the cloud region closer to where you are, this will help minimise the latency. Please note that you don't need to create a cloud account with the chosen provider, Aiven will handle everything for you.
  • Service plan: various options are available, from hobbyist to premium plans, covering all the scenarios from test to highly available production system. For our testing purposes the Hobbyist plan would be enough.
  • Service name: used to identify the service uniquely, we can either accept the default or write a more accurate name. Let's go for pg-jsonb-cheatsheet so we can immediately understand why we created the PostgreSQL instance.

After clicking on Create service, we need just a couple minutes of patience for the service to come up.

Once the service status is Running we can use our favourite tool to connect. If the chosen tool is psql, we can get the necessary command line, complete with connection details, by clicking on Quick connect. Otherwise, copy the Service URI, as highlighted, and use the tool of your choice.

Service overview page with Service URI highlighted

Insert the data

The cheatsheet includes a small JSON dataset (at the top left) that allows us to explore the functions. To start we need to execute that code to create a table called test containing a single record, with a serial number in id and a JSONB payload in the json_data column. The same JSON is shown below, so you can easily copy/paste it.

create table test(id serial, json_data jsonb);

insert into test(json_data) values (
'{
    "id": 778,
    "shop": "Luigis Pizza",
    "name": "Edward Olson",
    "phoneNumbers":
        ["(935)503-3765x4154","(935)12345"],
    "address": "Unit 9398 Box 2056\nDPO AP 24022",
    "image": null,
    "pizzas": [
        {
            "pizzaName": "Salami",
            "additionalToppings": ["🥓", "🌶️"]
        },
        {
            "pizzaName": "Margherita",
            "additionalToppings": ["🍌", "🌶️", "🍍"]
        }
    ]
}');
Enter fullscreen mode Exit fullscreen mode

Experience the JSONB functions

Now we're all set for success! Check out the cheatsheet, identify the problem to solve and copy/paste the relevant code.
For example, if you're looking to understand how to remove some fields from a JSON document, head to the Edit section, look for the Remove items in A example, copy and paste the code.

select json_data
    - ARRAY['pizzas','id']
    as no_pizzas_and_id
from test;
Enter fullscreen mode Exit fullscreen mode

The result is the original JSON document without the pizzas and id columns

                                                                           no_pizzas_and_id
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 {"name": "Edward Olson", "shop": "Luigis Pizza", "image": null, "address": "Unit 9398 Box 2056\nDPO AP 24022", "phoneNumbers": ["(935)503-3765x4154", "(935)12345"]}
(1 row)
Enter fullscreen mode Exit fullscreen mode

A quick lookup for JSONB functions

Being a good SQL citizen doesn't mean needing to know all the PostgreSQL JSONB functions by heart. The PostgreSQL JSONB cheatsheet is a one pager that can help you quickly find the function you're looking for to solve your semi structured data problem.

Some more links you might be interested to:

Top comments (4)

Collapse
 
ftisiot profile image
Francesco Tisiot

Hi Davin,
Both links seem to work for me… got any kore details?

Collapse
 
davinkevin profile image
Kevin Davin

I think you are blocked by pihole deny list 😓.

Collapse
 
ftisiot profile image
Francesco Tisiot

Should be fixed with new links

Collapse
 
davinkevin profile image
Kevin Davin

Great article! FYI the cheatsheet high resolution link is broken 🥲