100 Days of SQL

sql

Day 12 – SQL COUNT(), AVG() and SUM() Functions

In SQL, the COUNT(), AVG(), and SUM() functions are used to retrieve summary information about data in a table. These functions are often used in combination with the SELECT statement to calculate totals, averages, and counts.

  1. COUNT() function: The COUNT() function returns the number of rows that match a specified condition. The basic syntax is as follows:

SELECT COUNT(*) FROM table_name WHERE condition;

Here, * indicates that all rows in the table should be counted, and condition specifies the criteria for the rows to be included in the count.

For example, suppose you have a table called customers with columns customer_id, first_name, last_name, and email_address. If you want to count the number of customers in the table, you would use the following SQL statement:


SELECT COUNT(*) FROM customers;

This statement will return the total number of rows in the customers table.

  1. AVG() function: The AVG() function returns the average value of a numeric column in a table. The basic syntax is as follows:

SELECT AVG(column_name) FROM table_name WHERE condition;

Here, column_name is the name of the numeric column for which you want to calculate the average, and condition specifies the criteria for the rows to be included in the calculation.

For example, suppose you have a table called sales with columns product_name and sales_amount. If you want to find the average sales amount for all products, you would use the following SQL statement:


SELECT AVG(sales_amount) FROM sales;

This statement will return the average sales amount for all products in the sales table.

  1. SUM() function: The SUM() function returns the sum of the values in a numeric column in a table. The basic syntax is as follows:

SELECT SUM(column_name) FROM table_name WHERE condition;

Here, column_name is the name of the numeric column for which you want to calculate the sum, and condition specifies the criteria for the rows to be included in the calculation.

For example, suppose you have a table called sales with columns product_name and sales_amount. If you want to find the total sales amount for all products, you would use the following SQL statement:


SELECT SUM(sales_amount) FROM sales;

This statement will return the total sales amount for all products in the sales table.