Bird
Raised Fist0
MySQLquery~10 mins

Subqueries with EXISTS in MySQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Subqueries with EXISTS
Start Outer Query
↓
Check EXISTS Subquery
↓
Return Row
↓
Next Outer Row
↓
End
The outer query checks each row, then runs the EXISTS subquery. If the subquery finds any matching row, EXISTS is true and the outer row is returned. Otherwise, it skips that row.
Execution Sample
MySQL
SELECT name
FROM customers c
WHERE EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
This query returns names of customers who have at least one order.
Execution Table
StepOuter Row (c.id, c.name)EXISTS Subquery ConditionSubquery ResultEXISTS ResultOuter Query ActionOutput
1(1, 'Alice')SELECT 1 FROM orders WHERE customer_id=1Found rowsTRUEInclude rowAlice
2(2, 'Bob')SELECT 1 FROM orders WHERE customer_id=2No rows foundFALSESkip row
3(3, 'Carol')SELECT 1 FROM orders WHERE customer_id=3Found rowsTRUEInclude rowCarol
4(4, 'Dave')SELECT 1 FROM orders WHERE customer_id=4No rows foundFALSESkip row
5No more rows---End query
💡 No more outer rows to check, query ends.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
c.idN/A1234End
c.nameN/AAliceBobCarolDaveEnd
EXISTS ResultN/ATRUEFALSETRUEFALSEEnd
Output Rows[]['Alice']['Alice']['Alice', 'Carol']['Alice', 'Carol']['Alice', 'Carol']
Key Moments - 2 Insights
Why does the query include 'Alice' and 'Carol' but not 'Bob' or 'Dave'?
Because the EXISTS subquery found matching orders for Alice and Carol (see execution_table rows 1 and 3), so EXISTS is TRUE and those rows are included. For Bob and Dave (rows 2 and 4), no matching orders were found, so EXISTS is FALSE and those rows are skipped.
Does the subquery return data to the outer query?
No, the subquery only checks if any row exists that meets the condition. It returns TRUE or FALSE to the outer query, not the actual data. This is shown in the 'EXISTS Result' column in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the EXISTS Result for the outer row with c.id = 2?
ATRUE
BFALSE
CNo result
DDepends on orders
💡 Hint
Check the row where Outer Row is (2, 'Bob') in the execution_table.
At which step does the query stop checking outer rows?
AStep 3
BStep 4
CStep 5
DStep 1
💡 Hint
Look for the row with 'No more rows' in the Outer Row column in the execution_table.
If the orders table had an order for customer_id=4, what would change in the execution_table?
AEXISTS Result for c.id=4 would be TRUE and 'Dave' would be included in output
BNothing would change
CThe query would return an error
DAll rows would be skipped
💡 Hint
EXISTS depends on whether subquery finds rows; see execution_table row 4.
Concept Snapshot
Subqueries with EXISTS check if a subquery returns any rows.
Syntax: WHERE EXISTS (subquery)
If subquery finds rows, EXISTS is TRUE, outer row included.
If no rows, EXISTS is FALSE, outer row skipped.
Used to filter rows based on related data existence.
Full Transcript
This visual execution shows how a query with EXISTS works. For each row in the outer table 'customers', the database runs the subquery to check if there is at least one matching order in 'orders'. If the subquery finds any rows, EXISTS returns TRUE and the outer row is included in the result. If not, the row is skipped. The execution table traces each outer row, the subquery condition, whether rows were found, and the final decision to include or skip the row. Variables like c.id, c.name, and EXISTS result change step by step. Key moments clarify why some rows appear and others don't, and that EXISTS only returns TRUE or FALSE, not data. The quiz tests understanding of these steps and outcomes. This helps beginners see how EXISTS filters rows by checking related data presence.

Practice

(1/5)
1. What does the EXISTS keyword do in a MySQL query?
easy
A. Counts the total number of rows in a table
B. Deletes rows from a table based on a condition
C. Checks if a subquery returns any rows and returns TRUE or FALSE
D. Joins two tables together

Solution

  1. Step 1: Understand the purpose of EXISTS

    EXISTS checks if the subquery returns at least one row.
  2. Step 2: Compare with other options

    Counting rows, deleting rows, and joining tables are different operations.
  3. Final Answer:

    Checks if a subquery returns any rows and returns TRUE or FALSE -> Option C
  4. Quick Check:

    EXISTS means row presence check = B [OK]
Hint: EXISTS means "is there at least one row?" [OK]
Common Mistakes:
  • Confusing EXISTS with COUNT
  • Thinking EXISTS deletes rows
  • Mixing EXISTS with JOIN
2. Which of the following is the correct syntax to use EXISTS in a WHERE clause?
easy
A. SELECT * FROM table WHERE EXISTS = (SELECT column FROM table2);
B. SELECT * FROM table WHERE EXISTS SELECT column FROM table2;
C. SELECT * FROM table WHERE EXISTS IN (SELECT column FROM table2);
D. SELECT * FROM table WHERE EXISTS (SELECT column FROM table2);

Solution

  1. Step 1: Recall EXISTS syntax

    EXISTS must be followed by a subquery in parentheses.
  2. Step 2: Check each option

    SELECT * FROM table WHERE EXISTS (SELECT column FROM table2); uses correct syntax with parentheses; others have syntax errors.
  3. Final Answer:

    SELECT * FROM table WHERE EXISTS (SELECT column FROM table2); -> Option D
  4. Quick Check:

    EXISTS needs parentheses around subquery = C [OK]
Hint: EXISTS always uses parentheses for the subquery [OK]
Common Mistakes:
  • Omitting parentheses after EXISTS
  • Using '=' or 'IN' with EXISTS
  • Writing subquery without parentheses
3. Given tables customers(id, name) and orders(id, customer_id), what does this query return?
SELECT name FROM customers WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.id);
medium
A. An error because of invalid subquery
B. All customers who have placed at least one order
C. All orders with matching customer names
D. All customers including those without orders

Solution

  1. Step 1: Understand the EXISTS subquery

    The subquery checks if there is at least one order with customer_id matching customers.id.
  2. Step 2: Interpret the WHERE clause effect

    Only customers with matching orders exist, so only those customers are returned.
  3. Final Answer:

    All customers who have placed at least one order -> Option B
  4. Quick Check:

    EXISTS filters customers with orders = D [OK]
Hint: EXISTS filters rows with matching related data [OK]
Common Mistakes:
  • Thinking it returns all customers
  • Confusing orders with customers
  • Assuming syntax error in subquery
4. Identify the error in this query:
SELECT * FROM employees WHERE EXISTS SELECT * FROM departments WHERE departments.id = employees.dept_id;
medium
A. Missing parentheses around the subquery after EXISTS
B. Using SELECT * inside EXISTS is not allowed
C. The WHERE clause inside subquery is invalid
D. EXISTS cannot be used with multiple tables

Solution

  1. Step 1: Check EXISTS syntax

    EXISTS requires the subquery to be enclosed in parentheses.
  2. Step 2: Verify other parts

    SELECT * is allowed inside EXISTS; WHERE clause is valid; EXISTS works with multiple tables.
  3. Final Answer:

    Missing parentheses around the subquery after EXISTS -> Option A
  4. Quick Check:

    EXISTS needs parentheses = A [OK]
Hint: Always put subquery in parentheses after EXISTS [OK]
Common Mistakes:
  • Omitting parentheses after EXISTS
  • Thinking SELECT * is invalid inside EXISTS
  • Misunderstanding WHERE clause usage
5. You want to find all products that have never been ordered. Given tables products(id, name) and orders(id, product_id), which query correctly uses EXISTS to achieve this?
hard
A. SELECT name FROM products WHERE NOT EXISTS (SELECT 1 FROM orders WHERE orders.product_id = products.id);
B. SELECT name FROM products WHERE EXISTS (SELECT 1 FROM orders WHERE orders.product_id = products.id);
C. SELECT name FROM products WHERE EXISTS (SELECT 1 FROM orders WHERE orders.id = products.id);
D. SELECT name FROM products WHERE NOT EXISTS (SELECT 1 FROM orders WHERE orders.id = products.id);

Solution

  1. Step 1: Understand the goal

    We want products with no matching orders, so use NOT EXISTS with matching product_id.
  2. Step 2: Analyze each option

    SELECT name FROM products WHERE NOT EXISTS (SELECT 1 FROM orders WHERE orders.product_id = products.id); correctly uses NOT EXISTS with orders.product_id = products.id. SELECT name FROM products WHERE EXISTS (SELECT 1 FROM orders WHERE orders.product_id = products.id); finds products with orders. Options C and D compare wrong columns.
  3. Final Answer:

    SELECT name FROM products WHERE NOT EXISTS (SELECT 1 FROM orders WHERE orders.product_id = products.id); -> Option A
  4. Quick Check:

    NOT EXISTS filters products without orders = A [OK]
Hint: Use NOT EXISTS to find items with no related rows [OK]
Common Mistakes:
  • Using EXISTS instead of NOT EXISTS
  • Comparing wrong columns in subquery
  • Confusing product_id with order id
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard