Thursday, 1 June 2023

MySQL Aggregate Functions

MySQL aggregate functions are used to perform calculations on multiple values and return a single value. Some of the most common aggregate functions are:


COUNT(): Returns the number of rows in a group.

SUM(): Returns the sum of all values in a group.

AVG(): Returns the average of all values in a group.

MIN(): Returns the minimum value in a group.

MAX(): Returns the maximum value in a group.


Aggregate functions are often used with the GROUP BY clause to group rows together based on a common value. For example, the following query will return the number of orders for each product:


SQL

SELECT product_id, COUNT(*) AS num_orders

FROM orders

GROUP BY product_id;


The COUNT() function will count the number of rows in each group, and the GROUP BY clause will group the rows together based on the product_id column.


Aggregate functions can also be used without the GROUP BY clause. In this case, the aggregate function will be applied to all rows in the table. For example, the following query will return the average price of all products:


SQL

SELECT AVG(price) AS avg_price

FROM products;


The AVG() function will calculate the average price of all products in the products table.


I hope this helps! Let me know if you have any other questions.

No comments:

Post a Comment