Aggregate Function in SQL Server

In this blog, we will learn about aggregate function in SQL Server. An aggregate function is used to calculate the given values and returns a single value.

Types of aggregate functions in SQL Server.

  1. Count
  2. Avg
  3. Max
  4. Min
  5. Sum
  6. Count_Big
  7. Checksum_Agg

Count

This function returns the number of records in a table. The Count function can be classified into 3 types.
  1. count(*)
    It counts all the values including duplicate and null values in the table.

    Syntax
    select count(*) from student

  2. Count(<col name>)
    It counts all the values including duplicate but not null values.

    Syntax
    select count(Name) from student

  3. Count(Distinct<col name>)
    It counts the unique values.

    Syntax
    Select count(distinct name) from student

Distinct

This keyword is used for avoiding the duplicate values from a column in the table.

Example

Create a table.
  1. create table student(Id int ,Name varchar(50),city varchar(50),Marks int)  

Insert some values in the table.

  1. insert into student values(1,'A','J',56)  
  2. insert into student values(2,'B','N',56)  
  3. insert into student values(3,'C','G',96)  
  4. insert into student values(4,'D','D',81)  
  5. insert into student values(5,'E','A',51)  
  6. insert into student values(6,'F','H',66)  
  7. insert into student values(7,'G','B',76)  
  8. insert into student values(7,'G','B',76)  

Check the data in table.

  1. select * from student  
Aggregate Function in SQL Server

Now, check the count() function.

  1. select COUNT(*) from student  
 Result
 
Aggregate Function in SQL Server 

Select distinct Record.

  1. select COUNT(distinct Nameas DistinctRecord from student  
Result
 
Aggregate Function in SQL Server 

Avg()

It returns the average of a column value.
  1. select avg( Marks)As Avg from student   
Result
 
Aggregate Function in SQL Server 

Min()

This function returns the lowest value from the given values.
  1. select min( Marks)As MinimumMark from student   
 Result
 
Aggregate Function in SQL Server 
 

Max()

This function returns the highest value from the given values.
  1. select max( Marks)As MaxMark from student  
Aggregate Function in SQL Server

Sum()

This function returns the sum of the given values.
  1. select sum( Marks)As TotalMark from student   
Aggregate Function in SQL Server

Count_Big()

Count_Big is similar to the count function. The only difference is that count_big returns a bigint data type whereas the count function returns data type is int.
  1. select COUNT_big(*) from student  
Aggregate Function in SQL Server

Summary 

In this article, we learned about aggregate functions in SQL Server.