Menu
Coddy logo textTech

Built-In Aggregate Part 2

Part of the Fundamentals section of Coddy's SQL journey — lesson 35 of 72.

Sometimes we need to use aggregate functions in more complex ways, such as comparing each row with an aggregate value. This is where nested queries come in handy.

When you want to perform calculations that combine individual rows with aggregate values, you need to use a nested query. Here's why:
This won't work:

SELECT value + MIN(value)
FROM table1

The reason is that aggregate functions work on the entire column, while the 'value' reference is trying to work row by row. To solve this, we use a nested query:

SELECT value + (SELECT MIN(value) FROM table1)
FROM table1

This works because the nested query (SELECT MIN(value) FROM table1) is executed first and returns a single value, which can then be used in the main query for each row.

Common use cases for nested aggregates:
1. Comparing each value to the average

2. Calculating percentage of total

3. Finding differences from maximum or minimum values

challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>items</strong>: <strong>id</strong>, <strong>price</strong>

Calculate how much each item's price exceeds the average price of all items. Display the item ID, its price, and the difference from the average. Name the difference column as diff_from_avg.

Order the results by the difference in descending order.

Cheat sheet

When combining individual rows with aggregate values, use nested queries because aggregate functions work on entire columns while regular columns work row by row.

This won't work:

SELECT value + MIN(value)
FROM table1

Use a nested query instead:

SELECT value + (SELECT MIN(value) FROM table1)
FROM table1

The nested query executes first and returns a single value that can be used in the main query for each row.

Common use cases:

  • Comparing each value to the average
  • Calculating percentage of total
  • Finding differences from maximum or minimum values

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals