One of SQL's best features is the ability to use subqueries within a query, creating ad hoc tables that can be used to simplify queries that would otherwise melt your brain (or at least be difficult to read).
In this real-world example, we have a database of several thousand survey responses and want to be able to report on people's income. Normally we'd use SQL's COUNT
and GROUP BY
functions to report on totals, but the income field contains hundreds of distinct values - far too many to put into a chart.
Here's the query and the first few rows of the result:
SELECT Income, COUNT(Income) AS IncomeCount
FROM surveydata