PostgreSQL JSONB Cheatsheet –

by Blog Admin
0 comment

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

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 cheat sheet provides a set of consistent examples of all the most common JSONB functions and operators.

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. If you need the JSON functions instead, they’re really similar but without the b ending.

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+, including 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 favorite cloud provider and the cloud region closer to where you are. This will help minimize 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 systems. 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 of minutes of patience for the service to come up.

Once the service status is Running, we can use our favorite 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 cheat sheet 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 2056nDPO AP 24022",     "image": null,     "pizzas": [         {             "pizzaName": "Salami",             "additionalToppings": ["pepper", "tuna"]         },         {             "pizzaName": "Margherita",             "additionalToppings": ["banana"]         }     ] }');

Experience the JSONB Functions

Now we’re all set for success! Check out the cheat sheet, 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 and copy and paste the code.

select json_data     - ARRAY['pizzas','id']     as no_pizzas_and_id from test;

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 2056nDPO AP 24022", "phoneNumbers": ["(935)503-3765x4154", "(935)12345"]} (1 row)

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.

Here are some more links you might be interested in:

  • PostgreSQL JSON functions and operators
  • A more detailed version of PostgreSQL JSONB examples
  • An example of applying PostgreSQL JSON functions to find a restaurant in India

You may also like

Leave a Comment