Sobes.tech
Senior

What is an aggregate function in SQL?

sobes.tech AI

Answer from AI

An aggregate function in SQL is a function that takes a set of values and returns a single summary value. It is used to compute statistics or summarized data over a group of rows.

Main aggregate functions:

  • COUNT() — counts the number of rows or values
  • SUM() — sums the values
  • AVG() — calculates the average
  • MIN() — finds the minimum value
  • MAX() — finds the maximum value

Example of usage:

SELECT department, COUNT(*) AS employee_count, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;

Here, for each group of employees by department, the number of employees and the average salary are calculated.

Aggregate functions are often used together with GROUP BY for grouping data, and with HAVING for filtering groups based on aggregate conditions.