MySQL VAR_SAMP is one of the Aggregate Function, which is useful to calculate the Sample Variance of total records (or rows) selected by the SELECT Statement.
MySQL VAR_SAMP Formula
The mathematical formula behind the VAR_SAMP to calculate the sample variance is as shown below:
--Calculating Mean or Average Mean = Sum of each individual / Total number of items --Calculating the Sample Variance Sample Variance = ( (OriginalValue – Mean)² + (OriginalValue – Mean)² +.... ) / (Total number of items - 1)
The basic syntax behind the VAR_SAMP function in MySQL is as shown below:
-- VAR_SAMP in MySQL Syntax SELECT VAR_SAMP(Column_Name) FROM Source;
How to write VAR_SAMP function in MySQL to calculate the sample Variance with an example using the below-shown data?.
MySQL VAR_SAMP Example
The VAR_SAMP function returns the Simple Variance of total records present in a specified column. For example, the below query calculates the Sample Variance of all the records present in Yearly_Income from Customer details table.
-- MySQL VAR_SAMP example SELECT VAR_SAMP(Yearly_Income) AS `Simple income Variance` FROM customerdetails;
MySQL VAR_SAMP Group By Example
In general, the VAR_SAMP function calculates the Sample Variance of products belongs to a particular category or color, etc. In this situation, you can use the GROUP BY Clause to group the products by category. And next, use VAR_SAMP Function to calculate the Sample Variance.
-- MySQL VAR_SAMP Function Example USE company; SELECT Profession, VAR_SAMP(Yearly_Income) FROM customerdetails GROUP BY Profession;
The above VAR_SAMP query group the Customers by their Profession, and calculates their Sample Variance
For this demonstration, We are taking the Software Developer profession, and show you the VAR_SAMP output.
— Calculating Mean
Mean = (70000 + 79,000) / 2
Mean = 74,500
— Calculating Sample Variance
Variance = (70,000 – 74,500)² + (79,000 – 74,500)² / (2-1)
Variance = 40,500,000