Subqueries in SQL

Excellent ๐Ÿ‘
Now SUBQUERIES (IN, ANY, ALL) in the same crystal-clear pattern you want:

  • Base tables

  • Question

  • SQL

  • Actual OUTPUT table

  • ✔ Key explanation


๐Ÿ“˜ Base Tables (Used for ALL Subquery Examples)

customers

customer_idnamecity
1AmitPatna
2NehaDelhi
3RaviMumbai
4PoojaKolkata

suppliers

supplier_idsupplier_namecity
101ABC LtdDelhi
102XYZ PvtMumbai

products

product_idproduct_nameprice
1Pen10
2Book50
3Bag300
4Laptop50000

supplier_products

sp_idunit_price
120
2100
31000

orders

order_idorder_amount
1500
22000
37000

previous_orders

prev_idtotal_amount
11000
23000
36000

๐Ÿงพ Summary Table (Subquery Questions)

No.KeywordQuestion
1INCustomers from supplier cities
2ANYProducts cheaper than any supplier product
3ALLOrders greater than all previous orders

1️⃣ IN (Subquery)

Question: Show customers who live in cities where suppliers are located.

SELECT *
FROM customers
WHERE city IN (
  SELECT city
  FROM suppliers
);

✅ Output

customer_idnamecity
2NehaDelhi
3RaviMumbai

✔ Subquery returns list: Delhi, Mumbai
✔ IN checks if city matches any value in list


2️⃣ ANY (Subquery)

Question: Show products whose price is less than any supplier product price.

SELECT *
FROM products
WHERE price < ANY (
  SELECT unit_price
  FROM supplier_products
);

๐Ÿ” Subquery Result

unit_price = {20, 100, 1000}
Minimum = 20

✅ Output

product_idproduct_nameprice
1Pen10

< ANY means less than at least one value
✔ Equivalent to < MAX() logic


3️⃣ ALL (Subquery)

Question: Show orders whose amount is greater than all previous order amounts.

SELECT *
FROM orders
WHERE order_amount > ALL (
  SELECT total_amount
  FROM previous_orders
);

๐Ÿ” Subquery Result

total_amount = {1000, 3000, 6000}
Maximum = 6000

✅ Output

order_idorder_amount
37000

> ALL means greater than every value
✔ Equivalent to > MAX() logic


๐Ÿ”ฅ IN vs ANY vs ALL (Exam Gold Table)

KeywordMeaningEasy Logic
INMatches any value= OR OR OR
ANYCompare with at least one< MAX()
ALLCompare with all values> MAX() or < MIN()

๐Ÿง  One-Line Memory Trick

  • IN → is it in the list?

  • ANY → compare with one value

  • ALL → compare with every value


⚠️ Exam Traps

  • = ANY behaves like IN

  • > ALL means greater than maximum

  • ANY ≠ ALL


If you want next:

  • Correlated subqueries

  • EXISTS vs IN

  • Subqueries in SELECT / FROM

  • MCQs with output prediction

Just say ๐Ÿ‘

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.