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.

SqlData Fetching

Code

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

FAQ

Which tables or CTEs does it reference?
`teams`, `players`.