w3resource

How to Query JSON Data in PostgreSQL with JSONB?


Querying JSON Data in PostgreSQL

PostgreSQL supports JSON data types, making it a powerful tool for handling semi-structured data within a relational database. This functionality allows you to store, query, and manipulate JSON documents in PostgreSQL tables. Using JSON functions and operators, you can extract data from JSON columns, perform complex queries, and structure your data efficiently.

JSON Query Syntax and Examples

PostgreSQL provides two JSON data types: json (non-validated) and jsonb (binary, optimized for indexing and querying). The jsonb type is generally preferred for querying because it supports indexing and efficient storage.

Example 1: Querying a JSON Field

Assume you have a products table with a details column that stores product information in JSON format.

Code:

-- Create table with JSONB column
CREATE TABLE products (
    id SERIAL PRIMARY KEY,
    name TEXT,
    details JSONB
);

-- Insert sample data
INSERT INTO products (name, details) VALUES 
('Laptop', '{"brand": "Apple", "specs": {"ram": "16GB", "storage": "512GB"}}'),
('Phone', '{"brand": "Samsung", "specs": {"ram": "8GB", "storage": "128GB"}}');

Example 2: Extracting JSON Data with -> and ->>

1. -> Operator: Extracts JSON objects or arrays.

2. ->> Operator: Extracts JSON text (string) values.

Code:

-- Query to get the brand of each product
SELECT name, details->>'brand' AS brand FROM products;

Output:

-- name   | brand  
-- -------|---------
-- Laptop | Apple  
-- Phone  | Samsung

Example 3: Querying Nested JSON Data

You can also use the operators to access nested JSON data. For example, to get the ram specification from the specs object inside details:

Code:

-- Query to get the RAM of each product
SELECT name, details->'specs'->>'ram' AS ram FROM products;

Output:

-- name   | ram  
-- -------|------
-- Laptop | 16GB
-- Phone  | 8GB

Example 4: Filtering Based on JSON Data

You can use JSON fields in your WHERE clause for filtering.

Code:

-- Query to find products with a specific brand
SELECT * FROM products
WHERE details->>'brand' = 'Apple';

Output:

-- id | name   | details                                    
-- ----|--------|--------------------------------------------
--  1 | Laptop | {"brand": "Apple", "specs": {"ram": "16GB", "storage": "512GB"}}

Example 5: Using JSONB Functions

PostgreSQL provides additional functions to work with JSONB, such as jsonb_each_text() to retrieve key-value pairs.

Code:

-- Query to extract key-value pairs from details
SELECT name, jsonb_each_text(details) FROM products WHERE name = 'Laptop';

Output:

-- name   | jsonb_each_text                    
-- -------|-----------------------------------
-- Laptop | (brand,Apple)
-- Laptop | (specs,{"ram": "16GB", "storage": "512GB"})

Explanation of JSON Query in PostgreSQL

  • JSON Operators (->, ->>): These operators are essential for accessing JSON data, allowing you to retrieve both objects and text from JSON structures. The -> operator retrieves objects and arrays, while ->> retrieves text values.
  • Nested JSON Queries: With nested JSON structures, you can use the -> and ->> operators to access deeper levels of the JSON document.
  • Filtering with JSON: You can filter rows based on JSON values, allowing for flexible querying on semi-structured data without normalizing it into relational tables.
  • JSONB Functions: JSONB functions like jsonb_each_text() provide a way to interact with JSON data at a granular level, making it easier to extract specific information.

Using PostgreSQL’s JSON functionality, you can manage semi-structured data within your relational database, which can be helpful in applications that require both structured and flexible data storage.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/postgresql-json-query.php