Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
What Is Polardb for Postgresql?
Next article icon

What is JSONB in PostgreSQL?

Last Updated : 27 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

PostgreSQL is a powerful object-relational database management system that excels at handling structured and semi-structured data, especially through its support for JSONB. JSONB (Binary JSON) allows efficient storage and querying of JSON data and making it ideal for applications that require quick access to structured information.

In this article, we will explain JSONB in detail, explain how to manipulate it, and explain why JSONB is important in PostgreSQL with the help of practical examples.

Understanding JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. A basic example of a JSON object is:

Query:

{
"name": "John",
"age": 30,
"city": "New York"
}

JSONB in PostgreSQL

JSONB is a binary representation of JSON data in PostgreSQL, offering several key advantages over the standard JSON type:

  1. Speed: JSONB enables faster querying and data manipulation compared to JSON due to its binary storage format.
  2. Indexing: JSONB supports the creation of indexes, allowing for improved query performance, especially on large datasets.
  3. Efficient Storage: By storing data in a binary format, PostgreSQL can optimize how it organizes and retrieves this data.
  4. Flexible Querying: JSONB supports a variety of operators and functions that facilitate working with semi-structured data.

Creating a Products Table with JSONB

Let's create a database to manage product information using JSONB. You can insert data into the JSONB column using the ::jsonb cast. Here’s how you can insert product information into the products table. The name column stores the value 'Smartphone'.

  • The details column stores a JSONB object with the product's brand, model, and features.
  • The ::jsonb operator ensures the JSON string is converted to JSONB format.
  • The table will store product names and details in a JSONB column.

Query:

CREATE TABLE products (

id SERIAL PRIMARY KEY,

name TEXT,

details JSONB

);

INSERT INTO products (name, details)

VALUES (

'Smartphone',

'{"brand": "TechCorp", "model": "X100", "features": {"camera": "12MP", "battery": "4000mAh"}}'::jsonb

);

Output:

idnamedetails
1Smartphone{"brand": "TechCorp", "model": "X100", "features": {"camera": "12MP", "battery": "4000mAh"}}

Explanation:

  • This query yields a table by the name of the products with three columns: id, name, and details.
  • The details column is of type JSONB, which means it will hold the product attributes in JSON format.
  • A new row is inserted with the name value 'Smartphone' and details containing the JSON data.
  • After running this query, PostgreSQL will insert the product information into the table and return INSERT 0 1, confirming that one row has been added.

Overview of JSON Functions and Operators

JSON and JSONB support several functions and operators in PostgreSQL to perform several operations and functions. Some common operators include:

  • ->: Returns the value of one or more fields enclosed in curly braces and separated by commas using a single key to find an object.
  • ->>: Similarly to extracting field by key, to extract an object’s field it takes the form of JSON and returns it as text.
  • @>: Determines if one JSON object is nested in another JSON object.
  • #>: Get sub-object from JSON using path.

Retrieving and Querying JSONB Data

You can use the -> and ->> operators to query specific fields in a JSONB column. This query retrieves data from the products table, specifically targeting rows where the brand in the details JSONB field is 'TechCorp'. It extracts and returns the name of the product along with the camera specification found in the features field of the details JSONB column. Here's an example:

Query:

SELECT name, details->'features'->>'camera' AS camera_spec

FROM products

WHERE details->>'brand' = 'TechCorp';

Output:

product-table
Product table


Explanation:

This query retrieves the name of products where the brand is TechCorp and returns the camera specification from the details JSONB field.

Working with JSON Arrays in PostgreSQL

Arrays are also supported by JSONB, which is a data structure that store multiple data values in an ordered manner. It is also important to learn that we can insert and query JSON arrays in a similar way we do with JSON objects.

Query:

INSERT INTO products (name, details)

VALUES (

'Laptop',

'{"brand": "TechCorp", "model": "X200", "features": {"ports": ["USB-C", "HDMI", "Ethernet"]}}'::jsonb

);

Output:

json-arrays
Json Arrays

Explanation:

This query inserts a new product Laptop with various ports into the products table. The ports field is a JSON array stored in the details column.

JSON Arrays Using JSON Operators

This query uses the @> operator to check if the details JSONB column contains a specific value within its nested array. It filters for products that have "USB-C" listed under the "ports" in the "features" object. The query will return the name of products where this condition is met.

Query:

SELECT name

FROM products

WHERE details @> '{"features": {"ports": ["USB-C"]}}'::jsonb;

Output:

json-operators
Json operators

Explanation:

This query returns the name of products where the ports array in the features field containing "USB-C". The output shows that the Laptop product meets this condition.

Conclusion

PostgreSQL's JSONB data type allows for efficient storage and processing of JSON data, offering significant advantages in performance and flexibility over the standard JSON type. It is particularly beneficial for applications that require quick access to structured data, such as APIs and large data sets.


Next Article
What Is Polardb for Postgresql?

O

om7826pw5al
Improve
Article Tags :
  • PostgreSQL
  • Databases

Similar Reads

  • What is GIN in PostgreSQL?
    The GIN or Generalized Inverted Index, is one of the most powerful indexing techniques in PostgreSQL. It suits best indexing composite values, such as arrays, JSONB, or full-text search. In this article, we will learn about what GIN is, how it works along with their syntax and examples. What is GIN
    4 min read
  • What Is Polardb for Postgresql?
    PolarDB for PostgreSQL is a cloud-native database solution provided by Alibaba Cloud that is designed to offer high performance, scalability, and full compatibility with PostgreSQL. In this article, We will learn about What Is Polardb for PostgreSQL by understanding their Features, Examples and so o
    5 min read
  • What is an Index in PostgreSQL?
    PostgreSQL is a powerful and reliable open-source relational database management system (RDBMS) known for its extensive features, including robustness and scalability. One key feature of PostgreSQL that contributes to its high performance is indexing. Proper use of indexes can significantly improve
    5 min read
  • What is PostgreSQL - Introduction
    This is an introductory article for the PostgreSQL database management system. In this we will look into the features of PostgreSQL and why it stands out among other relational database management systems. Brief History of PostgreSQL: PostgreSQL also known as Postgres, was developed by Michael Stone
    2 min read
  • What is a Postgres Hosting?
    Postgres hosting gives businesses and developers a PostgreSQL database to host the issues of configuration, maintenance, and scaling that are supposed to be handled by the hosting provider. Options such as auto backups, Database performance tuning and the high availability of Postgres hosting make d
    6 min read
  • PostgreSQL - JSON Data Type
    JSON (JavaScript Object Notation) is a widely used format for storing data in the form of key-value pairs. Its popularity comes from being easy for humans to read and understand, making it ideal for communication between servers and clients. This readability and ease of use have made JSON a standard
    5 min read
  • What is JSON text ?
    JSON text refers to a lightweight, human-readable format for structuring data using key-value pairs and arrays. It is widely used for data interchange between systems, making it ideal for APIs, configuration files, and real-time communication. In today’s interconnected digital world, data flows seam
    4 min read
  • Install PostgreSQL on Mac
    Installing PostgreSQL on Mac OS can enhance our development environment, providing a robust relational database management system. In this article, we will focus on installing PostgreSQL version 11.3 using the installer provided by EnterpriseDB. This step-by-step guide will ensure a smooth installat
    4 min read
  • PostgreSQL - SELECT INTO
    The PostgreSQL SELECT INTO statement allows users to create a new table directly from the result set of a query. This command is ideal for duplicating or organizing data from an existing table into a new one for further analysis. SELECT INTO does not return data to the client but saves it in a new t
    4 min read
  • PostgreSQL - INSERT
    PostgreSQL INSERT statement is one of the fundamental SQL commands used to add new rows to a specified table within a PostgreSQL database. This command allows users to insert data efficiently, whether for a single record or multiple records at once. With the PostgreSQL INSERT INTO clause, we can spe
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences