Json Table Relational Projection
PostgreSQL 17 JSON_TABLE expands a JSON document into relational rows, declaring each column with name, type, and path, and NESTED PATH flattens inner arrays.
Code
-- PostgreSQL 17 的 JSON_TABLE:把 JSON 文档按 JSON 路径展开成关系行,
-- COLUMNS 逐字段声明名字、类型与取值路径,NESTED PATH 把内层数组摊平成多行
CREATE TABLE intake_forms (id int PRIMARY KEY, payload jsonb NOT NULL);
INSERT INTO intake_forms VALUES
(1, '{"applicant":"ada","skills":["sql","java"]}'),
(2, '{"applicant":"grace","skills":["plpgsql"]}');
SELECT
f.id,
jt.applicant,
jt.skill
FROM intake_forms f,
JSON_TABLE(
f.payload,
'$' COLUMNS (
applicant text PATH '$.applicant',
NESTED PATH '$.skills[*]' COLUMNS (skill text PATH '$')
)
) AS jt
ORDER BY f.id, jt.skill;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with intake_forms among the objects involved.
In terms of clauses, the statements use: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the intake_forms table.
Statements that matter
SELECT
f.id,
jt.applicant,
jt.skill
FROM intake_forms f,
JSON_TABLE(
f.payload,
'$' COLUMNS (
applicant text PATH '$.applicant',
NESTED PATH '$.skills[*]' COLUMNS (skill text PATH '$')
)
) AS jt
ORDER BY f.id, jt.skill;
INSERT INTO intake_forms VALUES
(1, '{"applicant":"ada","skills":["sql","java"]}'),
(2, '{"applicant":"grace","skills":["plpgsql"]}');
CREATE TABLE intake_forms (id int PRIMARY KEY, payload jsonb NOT NULL);
Interactive Tools for This Topic
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
FAQ
- Which tables appear in this script?
- The references are `intake_forms`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.