SQL SUM() AND AVG()

In this tutorial, we'll learn about the SQL SUM() AND AVG() functions with the help of various examples.

In SQL, SUM() and AVG() functions are used to calculate total and average values in numeric columns.


SQL SUM() Function

The SQL SUM() function is used to calculate the sum of numeric values in a column. For example,

SELECT SUM(amount) AS total_sales
FROM Orders;

Here, the SQL command returns the sum of amounts of all orders.

How to use SQL SUM() function
Example: SQL SUM() function

Let's take a look at another example.

SELECT SUM(amount) AS total_of_cus4
FROM Orders
WHERE customer_id = 4;

Here, the SQL command returns the total amount to be paid by the customer having id 4.

How to use SQL SUM() function with WHERE clause
Example: SQL SUM() function with WHERE clause

SQL AVG() Function

The SQL AVG() function is used to calculate the average of numeric values in a column. For example,

SELECT AVG(age) AS average_age
FROM Customers;

Here, the SQL command returns the average age of all customers.

How to use SQL AVG() function
Example: SQL AVG() function

Let's take a look at another example

SELECT DISTINCT customer_id, AVG(amount) AS average_spends
FROM Orders
GROUP BY customer_id;

Here, the SQL command returns the average spending of each customer.

How to use SQL AVG() function with GROUP BY clause
Example: SQL AVG() function with GROUP BY clause

Recommended readings

Did you find this article helpful?