AVG() and COUNT() in SQL Server

 

AVG() function

The AVG() function calculates the average value of a column in a table or in a set of rows, depending on how to used. One important thing on here that only numeric values can be passed to the AVG() function. We can use CONVERT() to return the numeric value of a number stored as text.


Summary:

SELECT AVG(Column_name)
FROM table_name

Example:

Suppose we have a table ‘tbl_employee’

Table name: tbl_Employee

Employee IdEmpNameSalaryDepartment
1Ankur1200Sales
2David3400Sales
3John1500HR
4James1200Production
5Mohan4500Production
6Ram2300HR

 

  1. Calculate the average value of a salary of employee .

SELECT AVG(salary) FROM tbl_Employee

And output will look like this:

2350

2. Calculate the average  salary in ‘HR’ department:

SELECT AVG(salary) FROM tbl_Employee WHERE Department=’HR’

And output will look like this:

1900

COUNT() function

COUNT() function in SQL Server is very common function that returns the count of the rows in the query that match a particular WHERE clause. We need to pass the asterisk to the count as COUNT(*) function to get a row  count from a query.

Summary:

SELECT COUNT(*)
FROM table_name

Example:

Suppose we have a table ‘tbl_employee’

Table name: tbl_Employee

Employee IdEmpNameSalaryDepartment
1Ankur1200Sales
2David3400Sales
3John1500HR
4James1200Production
5Mohan4500Production
6Ram2300HR

 

  1. Get the total numbers of the records in the table:

SELECT COUNT(*) FROM tbl_Employee

And output will look like this:

6

2. Get the total numbers of employees in ‘HR’ department:

SELECT COUNT(*) FROM tbl_Employee WHERE Department=’HR’

And output will look like this:

2