✏️ Explanatory Question

What is a derived table (inline view) in MySQL?

👁 10 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

47

What is a derived table (inline view) in MySQL?

Level: Advanced — A powerful technique for breaking complex queries into manageable pieces.

A derived table (also called an inline view) is a subquery placed in the FROM clause that acts as a temporary, virtual table for the outer query. The outer query then treats its result set just like a regular table.

Key rule: A derived table must be given an alias (e.g., AS dept_avg). Without an alias, MySQL throws a syntax error — "Every derived table must have its own alias."

Why Use Derived Tables?

  • Break a complex query into smaller, readable steps.
  • Pre-aggregate data (e.g., averages per group) then filter/join on it.
  • Apply conditions on aggregated results without repeating the aggregation.
  • Join a summarized result set with other tables.

Derived Table vs Regular Subquery

Aspect Derived Table WHERE Subquery
Location FROM clause WHERE / SELECT clause
Returns A full table Value(s) for comparison
Alias required? Yes (mandatory) No
Can be joined? Yes No

Quick Example

-- Derived table: average salary per department, then filter
SELECT dept_id, avg_salary
FROM (
    SELECT dept_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY dept_id
) AS dept_avg           -- alias is REQUIRED
WHERE avg_salary > 50000;

-- Join a derived table with another table
SELECT d.dept_name, t.emp_count
FROM departments d
JOIN (
    SELECT dept_id, COUNT(*) AS emp_count
    FROM employees
    GROUP BY dept_id
) AS t ON d.dept_id = t.dept_id;

-- Find the top earner in each department using a derived table
SELECT e.name, e.salary, e.dept_id
FROM employees e
JOIN (
    SELECT dept_id, MAX(salary) AS max_sal
    FROM employees
    GROUP BY dept_id
) AS m ON e.dept_id = m.dept_id AND e.salary = m.max_sal;
Derived table vs CTE: A derived table is defined inline in the FROM clause, while a CTE (Common Table Expression, using WITH) is defined before the main query — often cleaner and reusable. CTEs are covered in a later question.
Interviewer tip: The one-liner they want — "A derived table is a subquery in the FROM clause that acts as a temporary virtual table. It must have an alias and is ideal for pre-aggregating data before filtering or joining."