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.

SqlData Integrity

Code

snippet
-- 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

FAQ

Which tables or CTEs does it reference?
The references are `branches`.