Aggregate Functions

Estimated reading: 1 minute 14 views

1. What are aggregate functions in SQL?

Aggregate functions perform calculations on multiple rows of data and return a single result. Common aggregate functions:

  • SUM: Adds up all values.
  • AVG: Finds the average of values.
  • COUNT: Counts rows or non-NULL values.
  • MIN: Returns the smallest value.
  • MAX: Returns the largest value.

Example:

				
					SELECT SUM(salary), AVG(salary), COUNT(*), MIN(salary), MAX(salary) 
FROM employees;

				
			

2. Write a query to count the number of employees in a department.

Use the COUNT function with a GROUP BY clause to count employees in each department.
Example:

				
					SELECT department_id, COUNT(*) AS employee_count 
FROM employees 
GROUP BY department_id;

				
			

3. How can you use aggregate functions with the HAVING clause?

The HAVING clause filters groups after applying aggregate functions.

Example (Find departments with more than 5 employees):

				
					SELECT department_id, COUNT(*) AS employee_count 
FROM employees 
GROUP BY department_id 
HAVING COUNT(*) > 5;

				
			

Key Note: Use WHERE for row-level filtering and HAVING for filtering aggregated data.

Leave a Comment

Share this Doc

Aggregate Functions

Or copy link

CONTENTS