jsonb each text Unpack Pairs
Turn one JSON object per row into key/value pairs with jsonb_each_text, then filter or aggregate pairs that columns cannot express.
Code
-- 每行一个 JSON 对象:字段名不定,无法直接用列筛选
CREATE TABLE event_payloads (
id serial PRIMARY KEY,
payload jsonb NOT NULL
);
INSERT INTO event_payloads (payload) VALUES
('{"browser": "firefox", "plan": "pro"}'),
('{"browser": "safari", "plan": "free"}'),
('{"browser": "chrome", "plan": "pro", "beta": "on"}');
-- jsonb_each_text 把对象展开成 key/value 行
SELECT e.id, pair.key, pair.value
FROM event_payloads e,
jsonb_each_text(e.payload) AS pair(key, value)
ORDER BY e.id, pair.key;
-- 展开后就能做定列表达不了的条件:任意键命中某值
SELECT e.id, e.payload
FROM event_payloads e,
jsonb_each_text(e.payload) AS pair(key, value)
WHERE pair.value = 'pro';
DROP TABLE event_payloads;How it works
Several statements share this file — SELECT / INSERT / CREATE, with event_payloads among the objects involved.
Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; 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 event_payloads table.
Statements that matter
SELECT e.id, e.payload
FROM event_payloads e,
jsonb_each_text(e.payload) AS pair(key, value)
WHERE pair.value = 'pro';
INSERT INTO event_payloads (payload) VALUES
('{"browser": "firefox", "plan": "pro"}'),
('{"browser": "safari", "plan": "free"}'),
('{"browser": "chrome", "plan": "pro", "beta": "on"}');
SELECT e.id, pair.key, pair.value
FROM event_payloads e,
jsonb_each_text(e.payload) AS pair(key, value)
ORDER BY e.id, pair.key;
Interactive Tools for This Topic
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.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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- `event_payloads` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.