SQL
Use Subqueries for Advanced SQL Filtering
Learn to use subqueries to filter main query results based on conditions derived from another query, useful for complex data retrieval and analysis.
SELECT
product_name,
price
FROM
Products
WHERE
category_id IN (
SELECT
category_id
FROM
Categories
WHERE
category_name = 'Electronics'
)
AND price > (
SELECT
AVG(price)
FROM
Products
WHERE
category_id IN (
SELECT
category_id
FROM
Categories
WHERE
category_name = 'Electronics'
)
);
How it works: This snippet demonstrates using nested subqueries to perform more complex filtering. It first identifies the `category_id` for 'Electronics' products. Then, it selects products from this category whose price is above the average price of all products within the 'Electronics' category. This pattern is invaluable for queries where a condition for the main result set depends on the outcome of one or more independent queries.