13 / 13

What are derived tables?

Difficulty: 5/10
subqueries, performance optimization, query design

Derived tables in MySQL are temporary result sets created by a subquery in the FROM clause of a SQL query. Think of them as virtual tables generated on-the-fly for use within the main query.

Syntax:
What are they used for?
  1. 1

    Simplify complex queries by breaking them into manageable parts.

  2. 2

    Perform aggregations or transformations and reuse the result.

  3. 3

    Filter or order data in the subquery before applying further logic

  4. 4

    Avoid repeating subqueries by computing once and referring to it.

Suppose you want to find the top 3 highest-paid employees in each department.
Points to remember:
  1. 1

    Derived tables must have an alias (AS derived_table_name).

  2. 2

    You can't refer to a derived table more than once unless it's a Common Table Expression (CTE) or temporary table.

  3. 3

    They exist only during the execution of the query.

Scenario Questions

0-2 years experience

  1. 1We need to get each customer's latest order date along with their name. How would you write a MySQL query using a derived table to accomplish this?
  2. 2If you write a query with a derived table and then try to reference a column that isn’t selected in the outer SELECT, what happens?

2-5 years experience

  1. 1You added a derived table to a report query, but the performance dropped dramatically. How would you investigate and what alternatives might you consider?
  2. 2During a feature rollout, a colleague’s query using a derived table started returning duplicate rows. Walk me through how you’d debug the issue.

5-8 years experience

  1. 1Our analytics pipeline runs complex MySQL queries nightly, many of which use derived tables. How would you redesign those queries to improve scalability and reduce resource contention?
  2. 2When moving from MySQL 5.7 to 8.0, we noticed that some derived tables no longer use indexes as before. What architectural changes would you propose to mitigate this at the system level?

8+ years experience

  1. 1We are planning a migration from a monolithic MySQL database to a microservices architecture, and many existing reports rely on derived tables. How would you approach refactoring or replacing those derived tables to ensure long‑term maintainability across teams?
  2. 2Considering cross‑team data contracts, what guidelines would you set for when to use derived tables versus materialized views or separate services, and how would you enforce them?

Follow-up Questions

  • What are the trade‑offs between using a derived table and a CTE in MySQL?
  • How does MySQL handle indexing inside a derived table?
  • Can you describe a situation where you’d replace a derived table with a materialized view?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.