Cover Image for MySQL Aggregate Functions
103 views

MySQL Aggregate Functions

The MySQL provides several aggregate functions that allow you to perform calculations on a set of values and return a single result. These functions are often used in conjunction with the GROUP BY clause to group rows and apply aggregate functions to each group. Here are some common MySQL aggregate functions:

  1. COUNT(): Counts the number of rows in a result set or the number of non-null values in a column. Example:
   SELECT COUNT(*) FROM employees;
  1. SUM(): Calculates the sum of a numeric column. Example:
   SELECT SUM(salary) FROM employees;
  1. AVG(): Computes the average of a numeric column. Example:
   SELECT AVG(salary) FROM employees;
  1. MIN(): Retrieves the minimum value from a column. Example:
   SELECT MIN(salary) FROM employees;
  1. MAX(): Retrieves the maximum value from a column. Example:
   SELECT MAX(salary) FROM employees;
  1. GROUP_CONCAT(): Concatenates values from multiple rows into a single string, with an optional separator. Example:
   SELECT department, GROUP_CONCAT(employee_name) FROM employees GROUP BY department;
  1. STD() and STDDEV(): Calculate the standard deviation of a numeric column. STDDEV() is an alias for STD(). Example:
   SELECT STD(salary) FROM employees;
  1. VARIANCE(): Computes the variance of a numeric column. Example:
   SELECT VARIANCE(salary) FROM employees;
  1. BIT_OR(): Performs a bitwise OR operation on a numeric column. Example:
   SELECT BIT_OR(bit_flags) FROM data_flags;
  1. BIT_AND(): Performs a bitwise AND operation on a numeric column. Example: SELECT BIT_AND(bit_flags) FROM data_flags;

These aggregate functions can be used in combination with the GROUP BY clause to calculate aggregates for different groups of data within a table. For example, to calculate the total salary for each department, you would use GROUP BY with the SUM() function:

SELECT department, SUM(salary) FROM employees GROUP BY department;

Aggregate functions are powerful tools for summarizing data in your database and extracting meaningful insights from large datasets. They are commonly used in reporting and analytics to provide summary statistics for analysis.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS