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.
COUNT()
function: TheCOUNT()
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.
AVG()
function: TheAVG()
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.
SUM()
function: TheSUM()
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.