MySQL COUNT(), AVG() and SUM() Functions

In MySQL, the COUNT(), AVG(), and SUM() functions are used to perform aggregate calculations on a set of values in a table.

COUNT() Function

The COUNT() function returns the number of rows that match a specified condition.

The syntax for using the COUNT() function is:

SELECT COUNT(column_name) FROM table_name WHERE condition;

Here, column_name is the name of the column that you want to count, table_name is the name of the table where the column exists, and condition is an optional condition to filter the rows.

For example, to count the number of rows in a table called employees, you would use the following query:

SELECT COUNT(*) FROM employees;

This would return the total number of rows in the employees table.

AVG() Function

The AVG() function returns the average value of a numeric column in a table.

The syntax for using the AVG() function is:

SELECT AVG(column_name) FROM table_name WHERE condition;

Here, column_name is the name of the numeric column for which you want to calculate the average, and table_name is the name of the table where the column exists.

For example, to find the average salary of employees in a table called employees, you would use the following query:

SELECT AVG(salary) FROM employees;

SUM() Function

The SUM() function returns the sum of values in a numeric column in a table.

The syntax for using the SUM() function is:

SELECT SUM(column_name) FROM table_name WHERE condition;

Here, column_name is the name of the numeric column for which you want to calculate the sum, and table_name is the name of the table where the column exists.

For example, to find the total sales of a product in a table called sales, you would use the following query:

SELECT SUM(sales) FROM sales WHERE product = 'Product X';

These aggregate functions can also be used with the GROUP BY clause to perform calculations on groups of rows within a table.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial