SQL Development

Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single scalar value. They are often used with the GROUP BY clause to perform calculations on each group of rows.

Common Aggregate Functions

Using Aggregate Functions with GROUP BY

The GROUP BY clause groups rows that have the same values in one or more columns into a summary row, like "find the total sales for each region". Aggregate functions are typically used with GROUP BY.

Example: Calculating Average Salary per Department

Suppose you have an Employees table with Department and Salary columns.


SELECT
    Department,
    AVG(Salary) AS AverageSalary
FROM
    Employees
GROUP BY
    Department;
                

This query will return the average salary for each unique department found in the Employees table.

Using Aggregate Functions with HAVING

The HAVING clause is used to filter groups based on a specified condition. It is similar to the WHERE clause, but HAVING operates on the results of aggregate functions.

Example: Finding Departments with Average Salary Above a Threshold


SELECT
    Department,
    AVG(Salary) AS AverageSalary
FROM
    Employees
GROUP BY
    Department
HAVING
    AVG(Salary) > 60000;
                

This query returns only those departments where the average salary is greater than 60,000.

Note: When using aggregate functions without a GROUP BY clause, they operate on the entire result set of the query, returning a single value. If a GROUP BY clause is present, the aggregate function operates on each group separately.

Distinct Aggregate Values

You can use the DISTINCT keyword within an aggregate function to operate on unique values only.

Example: Counting Distinct Departments


SELECT
    COUNT(DISTINCT Department) AS NumberOfDistinctDepartments
FROM
    Employees;