EXISTS Subquery in SQL
Level 4135 keystrokes
EXISTS is true when its subquery returns at least one row; here it finds customers with an order over 500.
SQL code
-- Return the name and email of matching customers1SELECT2 name,3 email4FROM -- c is a short alias for customers, used inside the subquery5 customers c-- Keep the customer if the subquery finds at least one row-- Each customer appears once, however many big orders they have6WHERE EXISTS ( -- The selected value does not matter for EXISTS, so 1 is a common choice7 SELECT 18 FROM orders o -- Correlated: o.customer_id is compared with c.id of the current outer row9 WHERE o.customer_id = c.id -- Only orders over 500 count10 AND o.total > 50011)12ORDER BY13 name;Output
+-------+-------------------+ | name | email | +-------+-------------------+ | Alice | alice@example.com | | Bob | bob@example.com | +-------+-------------------+ 2 rows in set
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this SQL code and how often they appear.
.× 3_× 1,× 1;× 1(× 1)× 1=× 1>× 1