DEV Community

Cover image for Aggregate Functions in SQL
Morteza Mousavi
Morteza Mousavi

Posted on

Aggregate Functions in SQL

Often, when querying in SQL, it is necessary to obtain the sum of a series of numbers, such as the total salary. In SQL, specific functions have been defined for this operation, known as Aggregate Functions or Grouping Functions.

Aggregate Functions are used for grouping when working with numerical and statistical data, allowing us to obtain results after performing a series of basic or advanced mathematical calculations.

Aggregate Functions are predefined functions that, when configured during a database query according to our needs, perform the desired operations and return the results.

Functions like Sum and Count are examples of Aggregate Functions, and their main characteristic is that they return a single value based on specific calculations on the values of a column.

Next, we will examine these functions.
Min Function

This function is used to obtain the minimum value from similar values.

SELECT MIN(grade)
FROM StudentGrade;
Enter fullscreen mode Exit fullscreen mode

In the example above, we use this function to find the lowest score of students in the student grades table.
Max Function

This function is exactly the opposite of the Min function; it is used to find the maximum value among similar values.

SELECT MAX(salary)
FROM Personnel
WHERE Age < 35;
Enter fullscreen mode Exit fullscreen mode

In this example, it finds and displays the highest salary among personnel who are under 35 years old.
Sum Function

This function is used to obtain the sum of numbers.

SELECT SUM(Salary)
FROM Personnel;
Enter fullscreen mode Exit fullscreen mode

In this example, this function is used to sum all the salaries of the personnel in the personnel table.
Count Function

As the name of this function indicates, it is used to obtain the number of items.

SELECT COUNT(Id)
FROM Personnel;
Enter fullscreen mode Exit fullscreen mode

The Count function is used to find the number of personnel.
Avg Function

The AVG function is actually an abbreviation for “average.” Using the AVG function, we can calculate and display the average of the desired values from grouped columns.

SELECT AVG(Salary)
FROM Personnel;

Enter fullscreen mode Exit fullscreen mode

In this example, the AVG function is used to calculate the average salary of the personnel.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs