Scalar subquery cardinality errors: choose one row deliberately
Overview
Cardinality means the number of rows a query returns. A scalar expression needs one column and at most one row in PostgreSQL. SQLite may silently accept multiple rows, so a query that runs there can hide a portability bug.
First example
SELECT (SELECT id FROM orders WHERE customer_id = 1 ORDER BY id);Observed SQLite result (rows in JSON):
[ [ 101 ]]How it works
The first SQLite example intentionally shows the problematic query: customer 1 has orders 101 and 102. With the explicit ordering, SQLite returns 101, while PostgreSQL would reject the multiple rows. Do not use this as a portable selection pattern. If the task is to choose the greatest order ID, specify ORDER BY id DESC LIMIT 1 (the second example) or use MAX(id). If the task requires exactly one related row by business rule, enforce an appropriate unique key and investigate duplicates instead of masking them with LIMIT. A scalar query returning no row yields NULL; selecting two columns in a scalar context is also invalid. When several rows are needed, use a derived table, join or appropriate predicate instead.
Practical example
SELECT c.id, (SELECT o.id FROM orders o WHERE o.customer_id = c.id ORDER BY o.id DESC LIMIT 1) AS chosen_orderFROM customers c ORDER BY c.id;Observed SQLite result (rows in JSON):
[ [ 1, 102 ], [ 2, 103 ], [ 3, null ]]Practice and mistakes
Practice: choose the smallest order ID per customer, then predict 101, 103, NULL. Explain when LIMIT 1 would hide a data-integrity problem. Rewrite a scalar query to return all matching orders when the requirement is a list rather than one value.
PostgreSQL 17 example — NOT RUN
SELECT (SELECT id FROM orders WHERE customer_id = 1 ORDER BY id);Expected result, not executed: "cardinality violation (SQLSTATE 21000)"