bhylu.com

Advertisements

SQL Exists

EXISTS asks whether a subquery finds at least one row. It is a good fit for questions such as which customers have a paid order, without needing every matching order in the output.

Understand the idea

The subquery is correlated: it refers to customer_id from the outer customer row. SELECT 1 is a convention because the selected value is irrelevant; existence is what matters. A customer appears once even if several paid orders match. A join would need additional care if the output must remain one row per customer.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

SELECT c.name
FROM customers AS c
WHERE EXISTS (
  SELECT 1 FROM orders AS o
  WHERE o.customer_id = c.customer_id AND o.status = 'paid'
)
ORDER BY c.customer_id;

Read the result

Mira and Dev are returned. Asha has only a cancelled order, and Noor has no order. Neither satisfies the paid-order requirement.

Try one change

Use NOT EXISTS to find customers without a paid order. Confirm that Asha and Noor are both included.