Example 1
Find products priced above the average for their own category
For each product, the subquery computes the average price of all products in the same category. The Widgets average is 15: Widget A (10) falls below it and is excluded, Widget B (20) exceeds it and is returned. The Gadgets average is 40: Gadget Y (30) is excluded, Gadget X (50) is returned.
CREATE TABLE products (
id INT,
name VARCHAR(50),
category VARCHAR(50),
price INT
);
INSERT INTO
products
VALUES
(1, 'Widget A', 'Widgets', 10),
(2, 'Widget B', 'Widgets', 20),
(3, 'Gadget X', 'Gadgets', 50),
(4, 'Gadget Y', 'Gadgets', 30);SELECT
name,
price
FROM
products p
WHERE
price > (
SELECT
AVG(price)
FROM
products
WHERE
category = p.category
)
ORDER BY
name;| name | price |
|---|---|
| Gadget X | 50 |
| Widget B | 20 |
Identical syntax and result across all engines.