Skip to main content
Documents
Basic SyntaxMath FunctionsDate FunctionsJSON FunctionsDatabasesTables & Schema ManagementString FunctionsTriggersIndexes

PostgreSQL JSON vs. JSONB

PostgreSQL provides JSON functions to manipulate and query JSON data stored in the database. These functions are essential for handling JSON and JSONB data types, allowing users to extract and manipulate JSON content effectively.

Usage

JSON functions in PostgreSQL are used to access and manipulate JSON and JSONB data types, which are ideal for storing semi-structured data. These functions enable operations like extracting elements, converting data formats, and performing pattern matching.

sql
-- Extracting a JSON object field by key
SELECT json_column -> 'key' FROM table_name;

-- Extracting a JSONB object field by key
SELECT jsonb_column -> 'key' FROM table_name;

In these syntaxes, `->` is used to extract a JSON object, while `->>` is used to extract a text value from a JSON or JSONB column.

Additional JSON Functions

Here are some additional functions that can be useful:

  • `jsonb_set`: Updates values within a JSONB document.
  • `jsonb_insert`: Inserts a new value into a JSONB document at a specified path.
  • `jsonb_path_query`: Extracts JSONB values matching a specified JSONPath query.

Examples

1. Extracting a JSON Field

sql
SELECT data -> 'name' AS name
FROM users;

This example extracts the value of the `name` field from a JSON column `data` in the `users` table.

2. Converting JSON to JSONB

sql
SELECT data::jsonb
FROM users;

Here, a JSON column is cast to JSONB, which provides benefits like storage efficiency, performance improvements, and more efficient indexing and querying.

3. Complex Query with JSONB

sql
SELECT id, jsonb_array_elements(data->'items')->>'product_name' AS product_name
FROM orders;

This query extracts `product_name` from each element in the `items` array within a JSONB column `data`.

Tips and Best Practices

  • Choose JSONB for efficiency. JSONB is generally faster for querying and indexing and offers better storage efficiency compared to JSON.
  • Use appropriate operators. Familiarize yourself with JSON operators like `->`, `->>`, and `#>>` for extracting and manipulating data. For example, `->` extracts a JSON object, whereas `->>` extracts a text value.
  • Index JSONB columns. Create indexes on JSONB columns to speed up search operations.
  • Validate your JSON data. Ensure JSON data is valid before inserting it into the database to avoid runtime errors.
  • Use JSON functions judiciously. While powerful, JSON functions can be performance-intensive; use them when necessary.
  • When to choose JSON over JSONB. Opt for JSON when the original formatting and ordering of keys are important to your use case.

JSON Operators Summary

Operator Description
`->` Extracts JSON object
`->>` Extracts text value from JSON
`#>>` Extracts text value using path elements