Member-only story

SQL Mastery: 100 Unique Situations for Subqueries

btd
14 min readNov 12, 2023

--

1. Filtering Based on Aggregated Data:

  • Retrieve rows based on aggregated data, like finding employees with salaries above the average.
SELECT employee_name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

2. Nested Aggregations:

  • Nesting aggregates, such as finding employees with salaries above the average salary in their department.
SELECT employee_name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

3. Existence Check:

  • Check for the existence of records meeting certain conditions.
SELECT product_name
FROM products
WHERE EXISTS (SELECT 1 FROM orders WHERE orders.product_id = products.product_id);

4. Finding Maximum or Minimum Value:

  • Retrieve rows with the maximum or minimum value in a column.
SELECT employee_name
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

5. Subquery in the FROM Clause:

  • Using a subquery in the FROM clause to create a derived table.
SELECT department_name…

--

--

btd
btd

No responses yet