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 fieldMIN- Returns the min value of a fieldAVG- Returns the average value of a field
COUNT- Returns the total number of recordsSUM- 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 employeesOr to get multiple aggregates at once:
SELECT MAX(salary), MIN(salary), AVG(salary) FROM employeesChallenge
EasyAvailable 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_transactionsavg_quantitymax_unit_pricetotal_revenue
Cheat sheet
Aggregate functions calculate values over a field. Common aggregate functions:
MAX- Returns the max value of a fieldMIN- Returns the min value of a fieldAVG- Returns the average value of a fieldCOUNT- Returns the total number of recordsSUM- 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_nameExamples:
SELECT MAX(salary) FROM employeesSELECT MAX(salary), MIN(salary), AVG(salary) FROM employeesTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns