Row Value Comparisons Match Composite Keys

Compare row constructors directly to express composite key ranges, paginate by tuple order, and match multiple keys with IN.

SqlData Integrity

Code

snippet
CREATE TABLE events (
  tenant text NOT NULL,
  sequence bigint NOT NULL,
  payload text NOT NULL,
  PRIMARY KEY (tenant, sequence)
);

INSERT INTO events (tenant, sequence, payload)
VALUES
  ('acme', 1, 'created'),
  ('acme', 2, 'updated'),
  ('acme', 3, 'shipped'),
  ('globex', 1, 'created'),
  ('globex', 2, 'updated');

-- Row comparison follows lexicographic order of the listed columns.
SELECT tenant, sequence, payload
FROM events
WHERE (tenant, sequence) > ('acme', 1)
ORDER BY tenant, sequence;

-- Equality against multiple tuples works with IN.
SELECT tenant, sequence
FROM events
WHERE (tenant, sequence) IN (('acme', 3), ('globex', 1))
ORDER BY tenant, sequence;

-- The row constructor can also be expanded in a select list.
SELECT tenant,
       sequence,
       (tenant, sequence) < ('globex', 2) AS before_cutoff
FROM events
ORDER BY tenant, sequence;

How it works

Several statements share this file — SELECT / INSERT / CREATE, with events among the objects involved.

Breaking the statements into their working parts: 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 it in the events database context.

Statements that matter

SELECT tenant, sequence
FROM events
WHERE (tenant, sequence) IN (('acme', 3), ('globex', 1))
ORDER BY tenant, sequence;
SELECT tenant, sequence, payload
FROM events
WHERE (tenant, sequence) > ('acme', 1)
ORDER BY tenant, sequence;
INSERT INTO events (tenant, sequence, payload)
VALUES
('acme', 1, 'created'),
('acme', 2, 'updated'),
('acme', 3, 'shipped'),
('globex', 1, 'created'),
('globex', 2, 'updated');

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`events` — referenced directly, no join needed.