COUNT():
COUNT()
is used to count the number of rows in a result set or the number of non-null values in a column.Example 1:
sqlCopy code
SELECT COUNT(*) AS total_orders
FROM orders;
Output: The total number of orders in the "orders" table.
Example 2:
sqlCopy code
SELECT customer_id, COUNT(order_id) AS order_count
FROM orders
GROUP BY customer_id;
Output: The count of orders for each customer.
SUM():
SUM()
calculates the sum of values in a numeric column.Example:
sqlCopy code
SELECT SUM(total_amount) AS total_sales
FROM sales;
Output: The total sales amount.
AVG():
AVG()
calculates the average value of numeric data in a column.Example:
sqlCopy code
SELECT AVG(score) AS average_score
FROM exam_results;
Output: The average exam score.
MIN() and MAX():
MIN()
and MAX()
return the minimum and maximum values in a column, respectively.Example 1:
sqlCopy code
SELECT MIN(price) AS lowest_price
FROM products;
Output: The lowest product price.
Example 2:
sqlCopy code
SELECT MAX(salary) AS highest_salary
FROM employees;
Output: The highest employee salary.
GROUP_CONCAT() (MySQL-specific):
GROUP_CONCAT()
concatenates values from multiple rows into a single string within each group.Example:
sqlCopy code
SELECT department, GROUP_CONCAT(employee_name) AS employees_list
FROM employees
GROUP BY department;
Output: A comma-separated list of employees' names in each department.
STDEV() and VAR():
STDEV()
calculates the standard deviation, and VAR()
calculates the variance of a set of values.Example:
sqlCopy code
SELECT department, STDEV(salary) AS salary_std_dev, VAR(salary) AS salary_variance
FROM employees
GROUP BY department;
Output: The standard deviation and variance of salaries in each department.
BIT_AND() and BIT_OR():
BIT_AND()
performs a bitwise AND operation, and BIT_OR()
performs a bitwise OR operation on a set of values.Example:
sqlCopy code
SELECT department, BIT_AND(permission) AS all_permissions, BIT_OR(permission) AS any_permission
FROM user_permissions
GROUP BY department;
Output: The combined bitwise AND and OR results for permissions in each department.
COUNT(DISTINCT column):
COUNT(DISTINCT column)
counts the number of distinct (unique) values in a column.Example:
sqlCopy code
SELECT COUNT(DISTINCT product_category) AS unique_categories
FROM products;
Output: The count of unique product categories.
These aggregate functions are used to summarize and analyze data in SQL queries. They allow you to perform calculations on groups of rows, calculate statistics, and generate aggregated results based on specific criteria.