jsonb_populate_record Maps JSON To Rows
Map jsonb documents onto a composite type with jsonb_populate_record, including missing keys and ignored extras.
Code
CREATE TYPE contact AS (
name text,
email text,
age int
);
CREATE TABLE leads (
id int PRIMARY KEY,
payload jsonb NOT NULL
);
INSERT INTO leads (id, payload)
VALUES
(1, '{"name":"Ada","email":"[email protected]","age":36,"source":"web"}'),
(2, '{"name":"Grace","email":"[email protected]"}');
SELECT id,
(jsonb_populate_record(NULL::contact, payload)).*
FROM leads
ORDER BY id;
-- Missing keys become NULL; unknown keys are ignored.
SELECT (jsonb_populate_record(
NULL::contact,
'{"age":"41","email":"[email protected]"}'::jsonb
)).*;Inside the snippet
Several statements share this file — SELECT / INSERT / CREATE, with leads among the objects involved.
The SQL constructs in play: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
The leads table is the working surface here.
Key statements
INSERT INTO leads (id, payload)
VALUES
(1, '{"name":"Ada","email":"[email protected]","age":36,"source":"web"}'),
(2, '{"name":"Grace","email":"[email protected]"}');
SELECT (jsonb_populate_record(
NULL::contact,
'{"age":"41","email":"[email protected]"}'::jsonb
)).*;
SELECT id,
(jsonb_populate_record(NULL::contact, payload)).*
FROM leads
ORDER BY id;
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 objects does the SQL touch?
- `leads`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.