Postgres JSON_TABLE() function
Transform JSON data into relational views
The JSON_TABLE
function transforms JSON data into relational views, allowing you to query JSON data using standard SQL operations. Added in PostgreSQL 17, this feature helps you work with complex JSON data by presenting it as a virtual table which you can access with regular SQL queries.
Use JSON_TABLE
when you need to:
- Extract specific fields from complex JSON structures
- Convert JSON arrays into rows
- Join JSON data with regular tables
- Apply SQL operations like filtering and aggregation to JSON data
Function signature
JSON_TABLE
uses the following syntax:
Parameters:
json_doc
: JSON or JSONB data to processpath_expression
: SQL/JSON path expression that identifies rows to generateCOLUMNS
: Defines the schema of the virtual tablecolumn_definition
: Specifies how to extract values for each columnalias
: Name for the resulting virtual table
Example usage
Let's explore JSON_TABLE
using a library management system example. We'll store book information including reviews, borrowing history, and metadata in JSON format.
Create a test database
Query examples
Extract basic book information
This query extracts core book details from the JSON structure into a relational format.
Result:
book_id | title | isbn | author_name | publisher | pub_year |
---|---|---|---|---|---|
1 | The Art of Programming | 978-0123456789 | Jane Smith | Tech Books Inc | 2023 |
2 | Database Design Fundamentals | 978-0987654321 | Robert Johnson | Database Press | 2024 |
Analyze book reviews
This query flattens the reviews array into rows, making it easy to analyze reader feedback.
Result:
title | reviewer | rating | review_date | comment |
---|---|---|---|---|
Database Design Fundamentals | alice_wonder | 5 | 2024-03-01 | Comprehensive coverage of database concepts |
The Art of Programming | mary_jane | 4 | 2024-02-20 | Good examples, could use more exercises |
The Art of Programming | john_doe | 5 | 2024-01-15 | Excellent book for beginners! |
Track borrowing history
This query helps track book loans and current borrowing status.
Result:
title | user_id | checkout_date | return_status | condition |
---|---|---|---|---|
Database Design Fundamentals | U789 | 2024-03-01 | Still borrowed | excellent |
The Art of Programming | U456 | 2024-02-01 | 2024-02-15 | fair |
The Art of Programming | U123 | 2024-01-01 | 2024-01-15 | good |
Advanced usage
Aggregate review data
Use this query to calculate review statistics for each book.
Result
title | num_reviews | avg_rating | min_rating | max_rating |
---|---|---|---|---|
Database Design Fundamentals | 1 | 5.00 | 5 | 5 |
The Art of Programming | 2 | 4.50 | 4 | 5 |
Process arrays and metadata
This query extracts array fields and metadata into queryable columns.
Result:
title | genres | tags | edition |
---|---|---|---|
The Art of Programming | ["Programming", "Computer Science"] | ["algorithms", "python", "best practices"] | 2nd |
Database Design Fundamentals | ["Database", "Computer Science"] | ["SQL", "design patterns", "normalization"] | 1st |
Error handling
JSON_TABLE
returns NULL for missing values by default. You can modify this behavior with error handling clauses:
This example shows how to handle errors when extracting JSON data. There is an error here because the metadata
field is not of type TEXT
.
title | author_name | metadata | edition |
---|---|---|---|
The Art of Programming | Jane Smith | {} | 2nd |
Database Design Fundamentals | Robert Johnson | {} | 1st |
Performance tips
-
Create GIN indexes on JSONB columns:
-
Consider these optimizations:
- Place filters on regular columns before JSON operations
- Use JSON operators (
->
,->>
,@>
) when possible - Materialize frequently accessed JSON paths into regular columns
- Break large JSON documents into smaller pieces to manage memory usage