SQL Aggregate Functions

SQL aggregate functions enable developers to perform basic calculations across multiple rows in a database, answering questions like "how many," "what's the highest," or "what's the average value." In this tutorial, you will learn how to:

What are Aggregate Functions in SQL?

Aggregate functions allow you to perform calculations on a set of rows. The most commonly used functions include:

Always check your database's documentation to ensure the correct usage of aggregate functions. For SQLite, refer to the SQLite Aggregate Functions.

Using Aggregate Functions

Basic Queries

You can include aggregate functions directly in a SELECT clause. For example:

Using WHERE with Aggregates

To calculate aggregates on a subset of rows, use a WHERE clause:

SELECT COUNT(*) AS count 
FROM employees 
WHERE department = 'Sales';

Grouping Data with GROUP BY

The GROUP BY clause groups rows based on a column and performs aggregate calculations for each group.

Examples:

Sorting Aggregates with ORDER BY

You can order query results based on aggregate values using the ORDER BY clause.

Examples:

Filtering Aggregates with HAVING

Use HAVING to filter grouped data based on aggregate values. Unlike WHERE, which filters rows before grouping, HAVING filters groups after aggregation.

Example:

Return cities with more than one order:

SELECT COUNT(order_id) AS order_count, city, state 
FROM orders 
GROUP BY city, state 
HAVING order_count > 1 
ORDER BY order_count DESC;

Real-World Applications

SQL aggregate functions are essential in scenarios such as:

What You Learned

In this lesson, you learned:

By combining these techniques, you can perform advanced data analysis and generate insightful reports directly from your database.