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

The SQL COUNT (), AVG () and SUM () functions are aggregate functions, which are used to perform calculation on multiple rows and return a single value.All aggregate functions by default exclude nulls values before working on the data.

COUNT Function:
COUNT Function is used to return total number of rows that matches a specified criteria.COUNT(*) also considers Nulls and duplicates.

COUNT Function Syntax :

The syntax of the COUNT Function is −

SELECT COUNT(column-name)
FROM table-name
WHERE condition;
   



AVG() Functions :

AVG Function is used to return average value of rows that matches a specified criteria.AVG() function works only on numeric data types.



AVG() Functions Syntax :

The syntax of the AVG() Functions is −

SELECT AVG(column-name)
FROM table-name
WHERE condition;
   



SUM() Functions :

SUM Function is used to return total sum of rows that matches a specified criteria. SUM only works on numeric fields. Null values ​​are excluded from the returned result.



SUM() Functions Syntax :

The syntax of the SUM() Functions is −

SELECT SUM(column-name)
FROM table-name
WHERE condition;
   



SQL COUNT(), AVG() and SUM() Example :

Consider the Customer table with the following records -

CustomerID CustomerName Age Address CustomerSalary
1 Aarav 28 Udaipur 28000
2 Vivaan 25 Mumbai 30000
3 Reyansh 28 Chennai 35000
4 Muhammad 24 Udaipur 50000
5 Sai 30 Mumbai 27000


COUNT Example:- The following code is an example that will return the total customer IDs in the table.

SELECT COUNT(CustomerID)
FROM Customer;
   


The result for the respective sql query is as follows −

COUNT(CustomerID)
5



AVG Example:-The following code is an example that will return the average of CustomerSalary in the table.

SELECT AVG(CustomerSalary)
FROM Customer;
   


The result for the respective sql query is as follows −

AVG(CustomerSalary)
34000



SUM Example:- The following code is an example that will return the SUM of CustomerSalary in the table.

SELECT SUM(CustomerSalary)
FROM Customer;
   


The result for the respective sql query is as follows −

SUM(CustomerSalary)
170000



Visit :


Discussion


* You must be logged in to add comment.