Composite Type Row Field Access
Package related fields into a composite type, build values with ROW(...), and read them back with (col).field — the parentheses are required to disambiguate.
Code
-- composite type:把一组字段打包成行内对象
CREATE TYPE address AS (
city text,
zip text
);
CREATE TABLE branches (
id int PRIMARY KEY,
address address NOT NULL
);
INSERT INTO branches VALUES
(1, ROW('berlin', '10115')),
(2, ROW('paris', '75001'));
-- field access:点号取单个字段,列名前要加括号避免歧义
SELECT id,
(address).city,
(address).zip
FROM branches
ORDER BY id;
-- 整行展开成多列
SELECT id,
(address).*
FROM branches
ORDER BY id;
-- ROW 构造器整体替换复合值
UPDATE branches
SET address = ROW('lyon', '69001')
WHERE id = 2;
SELECT id, (address).city FROM branches WHERE id = 2;How the snippet works
SELECT / INSERT / UPDATE / CREATE statements share the script, touching branches.
Mechanically, the statements are built from: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The branches table is the working surface here.
Statements that matter
UPDATE branches
SET address = ROW('lyon', '69001')
WHERE id = 2;
SELECT id, (address).city FROM branches WHERE id = 2;
INSERT INTO branches VALUES
(1, ROW('berlin', '10115')),
(2, ROW('paris', '75001'));
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 or CTEs does it reference?
- The references are `branches`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.