🧚 Ascolta! Beekeeper Studio è una GUI per database veloce, moderna e open source Scarica
August 24, 2025 Di Matthew Rathbone

PostgreSQL’s JSONB data type facilitates the handling of JSON data within your database. Its capabilities go beyond simple storage, offering intricate functions enabling detailed manipulation and querying of JSON data. This guide will explore these JSONB functions with practical examples to help you leverage PostgreSQL’s power in managing JSON data.

For a broader overview of working with JSON in PostgreSQL, including both json and jsonb types, check out our comprehensive guide to PostgreSQL JSON functions.

Table of Contents

Introduction to JSONB

The jsonb data type in PostgreSQL is a binary format that stores JSON data. It’s highly efficient, offering indexing capabilities that json doesn’t have. JSONB is generally preferable due to its flexibility and performance benefits.

Creating a Table with JSONB

Let’s start by creating a table that uses the jsonb data type:

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    data JSONB
);

Inserting JSONB Data

Insert JSONB data using standard JSON syntax. PostgreSQL automatically validates and converts the JSON to binary format:

INSERT INTO users (data) VALUES 
('{"name": "John Doe", "email": "john@example.com", "age": 30}'),
('{"name": "Jane Doe", "email": "jane@example.com", "age": 25}'),
('{"name": "Alice Smith", "email": "alice@example.com", "age": 28, "address": {"city": "New York", "state": "NY"}}');

Accessing JSONB Values

PostgreSQL provides various operators to dig into JSONB values.

Extracting a JSONB Object

To access nested JSONB values, use the -> and ->> operators. The -> operator returns data in JSON format, while ->> returns text.

SELECT data->'name' AS name, data->>'email' AS email FROM users;

Expected Output:

  name   |       email        
---------+--------------------
 "John Doe" | john@example.com
 "Jane Doe" | jane@example.com

Extracting Nested JSONB Values

For deeper JSON structures, chain the operators. The ? operator checks for key existence first:

SELECT 
    data->>'name' AS name,
    data->'address'->>'city' AS city 
FROM users 
WHERE data ? 'address';

Expected Output:

    name     |   city   
-------------|----------
 Alice Smith | New York

JSONB Functions

PostgreSQL includes a suite of JSONB functions beyond simple value extraction.

Checking a Key Existence

The ? operator checks if a key exists:

SELECT data ? 'age' AS has_age FROM users;

Expected Output:

 has_age 
---------
 t
 t
 t

Checking Containment

Use the @> operator to verify if one JSON object contains another:

SELECT * FROM users WHERE data @> '{"age": 30}';

Expected Output:

 id |                    data                     
----+---------------------------------------------
  1 | {"name": "John Doe", "email": "john@example.com", "age": 30}

Concatenation of JSONB

Combine JSONB columns or values using the || operator:

SELECT data || '{"verified": false}' AS updated_data FROM users;

Expected Output:

                            updated_data                            
-------------------------------------------------------------------
 {"age": 30, "name": "John Doe", "email": "john@example.com", "verified": false}
 {"age": 25, "name": "Jane Doe", "email": "jane@example.com", "verified": false}
 {"age": 28, "name": "Alice Smith", "email": "alice@example.com", "address": {"city": "New York", "state": "NY"}, "verified": false}

Deleting a Key from JSONB

Remove a key using the - operator:

SELECT data - 'age' AS partial_data FROM users;

Expected Output:

                            partial_data                             
--------------------------------------------------------------------
 {"name": "John Doe", "email": "john@example.com"}
 {"name": "Jane Doe", "email": "jane@example.com"}
 {"name": "Alice Smith", "email": "alice@example.com", "address": {"city": "New York", "state": "NY"}}

JSONB Indexing

To improve the performance of queries on JSONB data, use indexes.

Creating a JSONB Index

A GIN index is ideal for JSONB types:

CREATE INDEX idx_users_data ON users USING GIN (data);

This index helps speed up operations like searching for the existence of JSON keys or key-value pairs.

Advanced JSONB Functions

PostgreSQL provides additional functions for more complex operations:

-- Convert JSONB to key-value pairs
SELECT jsonb_each_text(data) FROM users LIMIT 1;

-- Get all keys from a JSONB object
SELECT jsonb_object_keys(data) FROM users LIMIT 1;

-- Update a nested value using jsonb_set
UPDATE users 
SET data = jsonb_set(data, '{address,zip}', '"10001"')
WHERE data ? 'address';

Conclusion

PostgreSQL’s JSONB functions provide powerful, flexible options for working with JSON data within your database. The key advantages include:

  • Performance: Binary storage format with efficient indexing
  • Rich operators: Easy extraction and manipulation with ->, ->>, @>, ?
  • Advanced functions: Complex operations like jsonb_set, jsonb_each_text, and jsonb_array_elements
  • Indexing support: GIN indexes for fast querying

These capabilities make PostgreSQL an excellent choice for applications that need to store and query semi-structured JSON data alongside traditional relational data. By mastering these JSONB functions, you can build more flexible and efficient database applications.

Beekeeper Studio È Una GUI per Database Gratuita e Open Source

Il miglior strumento per query SQL ed editor che abbia mai usato. Fornisce tutto ciò di cui ho bisogno per gestire il mio database. - ⭐⭐⭐⭐⭐ Mit

Beekeeper Studio è veloce, intuitivo e facile da usare. Beekeeper supporta molti database e funziona benissimo su Windows, Mac e Linux.

La versione Linux di Beekeeper è al 100% completa, senza tagli e senza compromessi sulle funzionalità.

Cosa Dicono Gli Utenti Di Beekeeper Studio

★★★★★
"Beekeeper Studio ha completamente sostituito il mio vecchio workflow con SQL. È veloce, intuitivo e rende di nuovo piacevole lavorare con i database."
— Alex K., Sviluppatore Database
★★★★★
"Ho provato molte GUI per database, ma Beekeeper trova il perfetto equilibrio tra funzionalità e semplicità. Funziona e basta."
— Sarah M., Ingegnere Full Stack

Pronto a Migliorare il Tuo Workflow con SQL?

download Scarica Gratis