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.
Code
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
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.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.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.
FAQ
- Name the tables involved in this file.
- `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.