Menu
Coddy logo textTech

Built-In Aggregate Part 1

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

There are many built-in functions in SQL but we will cover the aggregate functions in this lesson.

An aggregate function receives a field as input and calculates something over this field. The most common aggregate functions are:

  • MAX - Returns the max value of a field
  • MIN - Returns the min value of a field
  • AVG - Returns the average value of a field
  • COUNT - Returns the total number of records
  • SUM - Return the sum of all non-null values in a field

You can use these functions in your SELECT statement like this:

SELECT MAX(col1), MIN(col2), AVG(col3), …

For example, to find the highest salary in an employees table:

SELECT MAX(salary) FROM employees

Or to get multiple aggregates at once:

SELECT MAX(salary), MIN(salary), AVG(salary) FROM employees
challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>sales</strong>: <strong>product_id</strong>, <strong>price_per_unit</strong>,  <strong>quantity</strong>

Write a query that returns:

  • The total number of sales transactions
  • The average quantity per sale
  • The maximum price per unit
  • The total revenue (sum of quantity * price_per_unit)

Your result should have these exact column names:

  • total_transactions
  • avg_quantity
  • max_unit_price 
  • total_revenue

Cheat sheet

Aggregate functions calculate values over a field. Common aggregate functions:

  • MAX - Returns the max value of a field
  • MIN - Returns the min value of a field
  • AVG - Returns the average value of a field
  • COUNT - Returns the total number of records
  • SUM - Return the sum of all non-null values in a field

Use aggregate functions in SELECT statements:

SELECT MAX(col1), MIN(col2), AVG(col3) FROM table_name

Examples:

SELECT MAX(salary) FROM employees
SELECT MAX(salary), MIN(salary), AVG(salary) FROM employees

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