Careeroza
Subqueries in FROM & SELECT
Derived Tables (FROM)
A subquery in FROM acts like a temporary table. It must have an alias.
Example
Average order value per customer, then only customers above 150:
SELECT t.CustomerID, t.AvgOrder
FROM (
SELECT CustomerID, ROUND(AVG(Amount), 2) AS AvgOrder
FROM Orders
GROUP BY CustomerID
) AS t
WHERE t.AvgOrder > 150;Result: 4 rows
| CustomerID | AvgOrder |
|---|---|
| 1 | 150.88 |
| 2 | 412 |
| 3 | 320.75 |
| 7 | 198.4 |
Scalar Subquery in SELECT
Example
Each product's price compared with its category average:
SELECT ProductName, Category, Price,
(SELECT ROUND(AVG(Price), 2) FROM Products p2 WHERE p2.Category = p.Category) AS CategoryAvg
FROM Products p;Result: 6 rows
| ProductName | Category | Price | CategoryAvg |
|---|---|---|---|
| Basmati Rice 5kg | Grocery | 12.5 | 11.25 |
| Green Tea 100 bags | Beverages | 6.75 | 12.38 |
| Olive Oil 1L | Grocery | 9.99 | 11.25 |
| Dark Chocolate | Snacks | 3.49 | 5.87 |
| Espresso Beans 1kg | Beverages | 18 | 12.38 |
| Almonds 500g | Snacks | 8.25 | 5.87 |
Tip: Scalar subqueries in SELECT run once per row. On big tables a join or window function is usually faster.