Course contents 08 / 17

08 / 17 · Combining Rows

Subqueries and existence

Use a query as a value or a membership test. Check for missing relationships and see how NULL changes NOT IN.

Prerequisites

Outer joins

The catalogue needs a flag for each product with at least one sale. The left join can keep mint in view and then summarize the matches, but it first makes three pairs for tea. For a flag, one qualifying line is enough. A subquery can express that condition directly.

A query can supply a value#

A subquery is a query nested inside another query. When it supplies a single value, it is a scalar subquery. To find the above-average lines, use the six order lines and calculate their mean amount inside the comparison. (PostgreSQL 18, §4.2.11; DuckDB 1.4, Scalar subquery)

SELECT order_id, line_no,
       quantity * unit_price_cents AS line_cents
FROM order_lines
WHERE quantity * unit_price_cents > (
    SELECT AVG(quantity * unit_price_cents)
    FROM order_lines
)
ORDER BY order_id, line_no;

The six amounts sum to 4400 cents. Their mean is 4400/64400 / 6, about 733.33 cents. Lines 103/1 and 104/1 both have amounts of 1200 and pass the comparison. The inner query has no reference to the surrounding row, so the same mean applies to all six candidates.

In PostgreSQL a scalar subquery needs one output column and at most one row. It yields NULL if there are zero rows and raises an error if there are several. For example, reading unit_price_cents from all coffee lines returns two rows. Their prices are both 600, but that is still two rows and a scalar subquery would fail. Reading the price from lines of mint gives zero rows and a scalar result of NULL. If a rule requires choosing the latest line, define which field gives the order and how to break ties before using ORDER BY … LIMIT 1. SQLite’s scalar subquery instead takes the first result row, so a query that appears to work there can still be ambiguous. (PostgreSQL 18, §4.2.11; SQLite, §11)

Check whether a match exists#

Use the catalogue setup in the same session. EXISTS tests whether its subquery has at least one result row. The inner condition refers to c.product from the outer query. This is a correlated subquery. To reason about it, hold the current catalogue row fixed while checking for an eligible order line. (PostgreSQL 18, §9.24.1; DuckDB 1.4, EXISTS)

SELECT c.product
FROM catalogue AS c
WHERE EXISTS (
    SELECT 1
    FROM order_lines AS l
    WHERE l.product = c.product
)
ORDER BY c.product;

Cocoa, coffee and tea pass. For tea, three inner rows satisfy the condition and EXISTS is true. The outer query keeps its one tea row. For mint, no inner row matches and EXISTS is false. SELECT 1 makes it clear that only presence matters. The predicate would also be true for a result consisting of one row whose only value is NULL. Negating the predicate with NOT EXISTS keeps just mint. The per-row interpretation defines the answer. It does not prescribe how often the DBMS executes the inner query. (PostgreSQL 18, §9.24.1; SQLite, §§10 and 12)

Figure

One match is enough

One match is enoughCocoa, coffee and tea have one, two and three matches. EXISTS is true for them. Mint has zero matches and EXISTS is false.productMatchesEXISTScocoa1TRUEcoffee2TRUEmint0FALSEtea3TRUE
Products have different numbers of sales. EXISTS only distinguishes zero from a positive count.

Qualifying the names matters. With both sides written as unqualified product in the inner query, PostgreSQL would resolve both to the inner table’s column. It would then compare each order line’s product to itself, independently of the current catalogue item. Because at least one such comparison is true, the erroneous EXISTS would keep mint too.

Test membership when values can be missing#

We can write the positive membership condition as c.product IN (SELECT product FROM order_lines). The subquery now produces one column of candidate values. Each of the three sold products has an equal value in that column, so the filtered result is the same as for EXISTS. Repeated candidate values leave membership unchanged. (PostgreSQL 18, §9.24.2)

A new sales file contains one identifiable product, tea, and a row whose code is still missing. We want to find catalogue codes that have no matching known code in the file. Try the two predicates side by side.

SELECT c.product,
       c.product NOT IN (
           SELECT product
           FROM (VALUES ('tea'::text), (NULL)) AS incoming(product)
       ) AS absent_in,
       NOT EXISTS (
           SELECT 1
           FROM (VALUES ('tea'::text), (NULL)) AS incoming(product)
           WHERE incoming.product = c.product
       ) AS absent_exists
FROM catalogue AS c
ORDER BY c.product;
productabsent_inabsent_exists
cocoaNULLTRUE
coffeeNULLTRUE
mintNULLTRUE
teaFALSEFALSE

For mint, equality with tea is false and equality with the missing code is unknown. The IN result is therefore unknown, and NOT IN still gives unknown. In the second predicate, neither comparison gives a true inner WHERE condition. The subquery produces no rows, making NOT EXISTS true. A WHERE with the first predicate would return no products, while the second would return three. (PostgreSQL 18, §§9.24.2–9.24.3; SQLite, §8)

With a non-null outer code and a subquery restricted to non-null codes, NOT IN and the corresponding NOT EXISTS equality test agree. Use the restriction when unknown codes should be ignored. If an unknown code may later turn out to be mint, no match in the current data does not prove that mint was unsold. The business rule must decide how to report that uncertainty.

Next#

An existence test keeps or drops each row of one input. Sometimes we need to combine both inputs, retain shared rows, or compare their multiplicities after projecting several fields. Set operations express those requests on complete query results.

References#

  1. PostgreSQL Global Development Group. PostgreSQL 18 documentation, 2025. §4.2.11 describes scalar result shape and outer references. §9.24 specifies EXISTS, IN and NOT IN.
  2. SQLite Project. SQL Language Expressions, §§8 and 10–12. Documents membership with missing values, correlation and SQLite’s first-row rule for scalar subqueries.
  3. DuckDB Foundation. Subqueries. DuckDB 1.4 documentation, sections on scalar subqueries and existence tests.