Aggregate functions in SQL are used to perform calculations on a set of values and return a single value as a result. These functions are often used in conjunction with the GROUP BY clause to summarize data based on a specific grouping criterion.
Here are some common aggregate functions in SQL:
COUNT: The COUNT function is used to count the number of rows in a table or a group of rows based on a specified condition. Here is an example:
SELECT COUNT(*) FROM customers;
This statement returns the total number of records in the customers table.
SUM: The SUM function is used to calculate the sum of a set of values. Here is an example:
SELECT SUM(order_total) FROM orders;
This statement returns the total order amount for all orders in the orders table.
AVG: The AVG function is used to calculate the average of a set of values. Here is an example:
SELECT AVG(salary) FROM employees;
This statement returns the average salary for all employees in the employees table.
MAX: The MAX function is used to find the maximum value in a set of values. Here is an example:
SELECT MAX(price) FROM products;
This statement returns the highest price among all products in the products table.
MIN: The MIN function is used to find the minimum value in a set of values. Here is an example:
SELECT MIN(quantity) FROM inventory;
This statement returns the lowest quantity among all items in the inventory table.
Aggregate functions are useful for summarizing and analyzing data in SQL. They can be used to calculate various metrics and statistics, such as total sales, average ratings, and maximum and minimum values. By using aggregate functions, you can quickly derive insights and draw conclusions from large data sets in your database.