Structured Query Language (SQL) is a programming language used to manage and manipulate relational databases. SQL provides a variety of functions to perform calculations on data stored in tables. Three of the most commonly used functions are COUNT, AVG, and SUM.
The COUNT function is used to count the number of rows in a table that meet a certain condition. The syntax for the COUNT function is as follows:
SELECT COUNT(column_name) FROM table_name WHERE condition;
The COUNT function can also be used without a WHERE clause to count all the rows in a table. For example:
SELECT COUNT(*) FROM table_name;
This will return the total number of rows in the table.
The AVG function is used to calculate the average value of a column in a table. The syntax for the AVG function is as follows:
SELECT AVG(column_name) FROM table_name WHERE condition;
The AVG function can also be used without a WHERE clause to calculate the average of all the values in a column. For example:
SELECT AVG(column_name) FROM table_name;
This will return the average value of the column.
The SUM function is used to calculate the sum of a column in a table. The syntax for the SUM function is as follows:
SELECT SUM(column_name) FROM table_name WHERE condition;
The SUM function can also be used without a WHERE clause to calculate the sum of all the values in a column. For example:
SELECT SUM(column_name) FROM table_name;
This will return the sum of the column.
Here are some examples of how to use the COUNT, AVG, and SUM functions in SQL:
SELECT COUNT(*) FROM customers;
This will return the total number of rows in the customers table.
SELECT AVG(price) FROM products WHERE category = 'Electronics';
This will return the average price of all the products in the Electronics category.
SELECT SUM(quantity) FROM orders WHERE customer_id = 123;
This will return the total quantity of products ordered by the customer with ID 123.