EXISTS Operator in SQL

Level 496 keystrokes

EXISTS returns TRUE if the subquery returns at least one row; here it finds customers with any order.

SQL code

-- Return the names of matching customers
1SELECT
2 name
3FROM
-- c is an alias the subquery uses to refer to the current customer
4 customers c
5WHERE
-- TRUE as soon as the subquery finds one row; the search can stop there
6 EXISTS (
-- Only existence matters, so the selected value is just 1
7 SELECT 1
8 FROM orders o
-- Correlated: look for orders of the current customer c.id
9 WHERE o.customer_id = c.id
10 );

Output

+-------+
| name  |
+-------+
| Alice |
| Bob   |
+-------+
2 rows in set
Practice typing this code

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.

  • .× 2
  • _× 1
  • ;× 1
  • (× 1
  • )× 1
  • =× 1

More SQL examples at level 4

← SQL typing practice