...

/

Introduction to Aggregate Functions

Introduction to Aggregate Functions

Learn about aggregate functions in SQL.

Suppose our online store is doing great and receives hundreds of orders every day. As the year comes to an end, there are certain questions we want to answer to identify trends in our sales. For example, we might want to analyze:

  • What is the total revenue generated this month?

  • How many orders have been placed in total?

  • What is the average price of products sold?

This is where aggregate functions come in. Instead of doing the calculations manually, these functions allow us to get the answers in a straightforward and efficient manner.

Let’s explore the aggregate functions in SQL and understand how they help us analyze the data. We’ll go step by step to:

  • Understand what aggregate functions are and why they are useful.

  • Learn how to use COUNT, SUM, AVG, MIN, and MAX to analyze data.

  • Learn how to combine aggregate functions in a single query.

  • Understand the importance of using aggregate functions on appropriate data types.

What are aggregate functions?

Aggregate functions are special SQL functions that operate on a group of rows and return a single summarizing value. They allow us to quickly calculate the total number of orders placed, the total revenue generated in a month, the average price of products, and other similar metrics.

Aggregate functions work seamlessly with the SELECT statement and can be combined with clauses like WHERE for more refined results. We typically write a query with aggregate function as follows:

Press + to interact
SELECT AGGREGATE_FUNCTION(Column1)
FROM TableName;

The structure above applies the aggregate function on Column1 of the defined table. 

Common aggregate functions in SQL

In SQL, there are several commonly used aggregate functions, each with its own specific use case. Let’s explore them one by one:

The COUNT() function

The COUNT() function returns the number of rows in a dataset based on the ...