What is the largest number of courses that one instructor teaches? First count per instructor, then take the maximum of the counts. One query cannot do both:
text
SELECT MAX(COUNT(*)) FROM teaches GROUP BY id;
ERROR: aggregate function calls cannot be nestedPut the first step in FROM:
sql
SELECT MAX(n)
FROM (
SELECT id, COUNT(*) AS n
FROM teaches
GROUP BY id
) AS per_instructor;per_instructor (the subquery's result)
| id | n |
|---|---|
| I101 | 2 |
| I102 | 1 |
| I106 | 2 |
| I103 | 1 |
- A subquery in
FROMis a derived table. The outer query reads its result like a table. - Give it an alias (
AS per_instructor). Use the alias before its columns, as with any table. - Name each computed column (
COUNT(*) AS n). The outer query needs a name to use it. - A derived table can be joined to other tables, filtered with
WHEREand grouped again.