// SQL snippet

Exists flag in SELECT

EXISTS inside CASE stops at the first match, so it stays cheap even on big children.

Main statement
All engines

The task

You want a customer list with a has-returns column, without joining orders and without inflating rows.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT c.id, c.name,
       CASE WHEN EXISTS (
         SELECT 1
         FROM orders o
         WHERE o.customer_id = c.id
           AND o.status = 'returned'
       ) THEN 1 ELSE 0 END AS has_returns
FROM customers c
ORDER BY c.name;

工作原理

For each customer the subquery just asks whether one matching order exists; the engine stops scanning at the first hit. No join means no duplicate rows to dedupe and no aggregate to keep in step with GROUP BY. PostgreSQL, MySQL, SQLite and Oracle 23ai also let you select the bare EXISTS (...) AS has_returns; SQL Server does not, so the CASE with 1/0 is the portable spelling.

Variations

Bare boolean column (PostgreSQL, MySQL, SQLite, Oracle 23ai)

PostgreSQL MySQL SQLite Oracle
SELECT c.id, c.name,
       EXISTS (
         SELECT 1
         FROM orders o
         WHERE o.customer_id = c.id
           AND o.status = 'returned'
       ) AS has_returns
FROM customers c
ORDER BY c.name;

Questions that come up

Why not a LEFT JOIN with COUNT?

A join fetches every matching order just to answer yes/no, and needs a GROUP BY to fold the rows back to one per customer. EXISTS stops at the first match (an index on (customer_id, status) makes that a single seek) and adds one column, nothing more.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.