DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Modify JSON Data in Postgres and Hibernate 6
  • Postgres JSON Functions With Hibernate 6
  • Postgres JSON Functions With Hibernate 5
  • Comparing Managed Postgres Options on The Azure Marketplace

Trending

  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Caching 101: Theory, Algorithms, Tools, and Best Practices
  1. DZone
  2. Coding
  3. Languages
  4. PostgreSQL JSONB Cheatsheet: Complete and Fast Lookup Guide

PostgreSQL JSONB Cheatsheet: Complete and Fast Lookup Guide

This PostgreSQL JSONB Cheatsheet presents a complete guide to PostgreSQL JSONB functions with examples and some demo code.

By 
Francesco Tisiot user avatar
Francesco Tisiot
·
May. 19, 23 · Code Snippet
Likes (1)
Comment
Save
Tweet
Share
4.4K Views

Join the DZone community and get the full member experience.

Join For Free

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.

JSON
 
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": ["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.

JSON
 
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.

JSON
 
                                                                           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)


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
JSON PostgreSQL

Published at DZone with permission of Francesco Tisiot. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Modify JSON Data in Postgres and Hibernate 6
  • Postgres JSON Functions With Hibernate 6
  • Postgres JSON Functions With Hibernate 5
  • Comparing Managed Postgres Options on The Azure Marketplace

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!