SQL LESSON 18 OF 32

EXISTS & correlated subqueries

A correlated subquery refers to a row in the outer query. EXISTS checks whether at least one matching row exists. It does not multiply customer rows when several orders match.

हिन्दी में समझें

कोरिलेटेड सबक्वेरी बाहरी पंक्ति का मान लेती है। EXISTS कम से कम एक मेल जाँचता है। कई orders मिलने पर भी ग्राहक की पंक्ति नहीं दोहराता।

अभ्यास: कम से कम एक pending order वाले ग्राहक name, id क्रम में।

Hinglish mein samjhein

Correlated subquery outer row ko refer karta hai. EXISTS kam se kam ek matching row check karta hai. Multiple orders par customer duplicate nahi hota.

Practice: Ek bhi pending order wale customer names, customer id sorted.

A small SQL example

SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id=c.id) ORDER BY c.id;

Examples use the fictional shop database bundled with the SQL playground: customers, products, orders, order_items and employees. The engine is SQLite; other SQL dialects may differ.

Try this example in the SQL playground →

Practise this idea

Find customer names with at least one pending order, ordered by customer id.

Check answer & explanation
SELECT c.name FROM customers c WHERE EXISTS(SELECT 1 FROM orders o WHERE o.customer_id=c.id AND o.status='pending') ORDER BY c.id;

The correlated subquery searches orders belonging to the current customer. EXISTS includes that customer once when any pending order matches.

Stuck in the course? Choose Check answer for either the challenge or quiz. Read the explanation and continue to the next lesson at your own pace.

Check your understanding

EXISTS asks whether…

  1. At least one matching row exists
  2. All rows are equal
  3. A table is sorted
Check the quiz answer

At least one matching row exists

A correlated subquery refers to a row in the outer query. EXISTS checks whether at least one matching row exists. It does not multiply customer rows when several orders match.

References & corrections

Use the official SQLite documentation for full language rules. Read how these lessons are made and checked. Found a mistake? Report it to Excel Keys with this lesson URL and a reproducible example.

FROM LEARNING TO BUSINESS RESULTS

Need a dashboard for your team?

Excel Keys designs custom Excel and HTML dashboards around your own KPIs and Excel files. They run offline in the browser, so your data stays on your computer.