Skip to content
SQLSimplified
subquery

Derived Table: Subquery in the FROM Clause

Wrap an aggregated subquery in FROM to rank products by total revenue.

Overview

A subquery in the FROM clause is called a derived table (or inline view). It produces a temporary result set you can join and aggregate further. Here we first compute per-product revenue, then rank those products by revenue — a two- stage aggregation that's clean as a derived table.

The Query

Store (Customers/Orders/Products)

Loading database engine...

Step-by-Step Breakdown

  1. Inner subquery computes total revenue per product.
  2. ranked subquery does the same but adds a RANK() window over revenue.
  3. We select from ranked (joined to prod merely to demonstrate aliasing) and order by rank.

Derived tables need aliases

Every derived table must have an alias (here prod, ranked) or the query fails to parse.

Variations

Simpler single derived table with revenue and rank:

Store (Customers/Orders/Products)

Loading database engine...

Common Mistakes

  • Missing alias on the derived table. FROM (…) without AS alias is a syntax error.
  • Referencing outer columns. A derived table can't see columns from the outer query (that's what correlated subqueries/LATERAL are for).
  • Duplicate column names. Join two derived tables with overlapping column names and you must qualify them everywhere.

Search

Search lessons, functions, examples, and practice problems