Scalar Subquery Returns At Most One Row
A scalar subquery may return at most one row; a second matching row aborts the whole statement with a cardinality error.
Code
-- a scalar subquery sits in expression position and returns at most one row
CREATE TABLE teams (
team_id int PRIMARY KEY,
region text NOT NULL
);
INSERT INTO teams VALUES (1, 'east'), (2, 'east'), (3, 'west');
CREATE TABLE players (
player_id int PRIMARY KEY,
team_id int NOT NULL REFERENCES teams(team_id)
);
INSERT INTO players VALUES (10, 1), (11, 3);
-- ok: looked up by primary key, naturally at most one row
SELECT player_id,
(SELECT region FROM teams t WHERE t.team_id = p.team_id) AS region
FROM players p;
-- crash: region is not unique, so two rows for the same value raise a cardinality error for the whole statement
-- ERROR: more than one row returned by a subquery used as an expression
-- SELECT player_id,
-- (SELECT region FROM teams WHERE region = 'east') AS region
-- FROM players;How the snippet works
The file runs SELECT / INSERT / CREATE statements, touching teams and players.
Breaking the statements into their working parts: a WHERE clause filtering the rows one statement applies to; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard tying rows to the parent table.
Applying it
The teams table is the working surface here.
Statements that matter
SELECT player_id,
(SELECT region FROM teams t WHERE t.team_id = p.team_id) AS region
FROM players p;
CREATE TABLE players (
player_id int PRIMARY KEY,
team_id int NOT NULL REFERENCES teams(team_id)
);
CREATE TABLE teams (
team_id int PRIMARY KEY,
region text NOT NULL
);
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?
- `teams`, `players`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.