How to Calculate the Average of a Numerical Column SQL Server

This tutorial will show how to calculate the average of a numerical column with the AVG function in SQL Server. The AVG function returns the average value of a numeric column and allows the programmer to use a column alias for the output for a more descriptive column name.

Setting Up

For this tutorial we will be using a table called Orders with columns of O_Id, OrderDate, OrderPrice, and Customer. To create a table in SQL Server, we use the CREATE TABLE statement to specify the name of the table, name columns and define what data types they are to be.

 

 

Now that we created a table, we can insert data into it. We can insert data with the INSERT INTO, SELECT, and UNION statements. The INSERT INTO statement allows the programmer to specify what table to insert values into, the SELECT statement adds data into the table, and the UNION statement does not allow duplicates in the table.

 

 

The AVG Function

Now that we have a table and data to work with, we can use the AVG function to retrieve and output the average price in the OrderPrice column.

The query simply uses the SELECT statement and calls the AVG function immediately on the OrderPrice column. After the average is calculated, we will display the results in a OrderAverage column alias.

 

 

Output

Execute the query and a one column, one row table will be outputted.

As you can see in the screen shot, the average number in the OrderPrice column is 1171. The AVG function is built in SQL Server to make getting averages in number columns easier, allowing for easier manipulation from the programmer.

Thanks for reading and make sure to download the source files to get a better understanding of how the code works.

Leave a Reply

Your email address will not be published. Required fields are marked *