SQL Development Documentation

VAR() - SQL Aggregate Function

The VAR() aggregate function computes the statistical variance of a set of numbers. Variance measures how spread out a set of numbers is from their average value. A low variance indicates that the data points tend to be very close to the mean (also called the expected value) of the set, while a high variance indicates that the data points are spread out over a wider range of values.

Syntax

The general syntax for the VAR() function is:

VAR(expression) [ OVER ( [ partition_clause ] order_clause ) ]

Parameters

Parameter Description
expression An integer, float, or money-type numeric expression that returns a value from the set of numbers over which the variance is to be calculated. It cannot be a column of a large object (LOB) data type, or a bit, image, text, ntext, xml, sql_variant, geography, or geometry data type.

Return Type

The VAR() function returns the variance of the specified expression. The return type depends on the input expression's data type. For example, if the input is an integer, the output might be a float.

Remarks

Example 1: Basic Variance Calculation

This example calculates the variance of salaries in an 'Employees' table.

SELECT VAR(Salary) AS SalaryVariance
FROM Employees;

Example 2: Variance within Departments (using OVER clause)

This example calculates the variance of salaries for each department, showing the variance relative to the entire dataset and also partitioned by department.

SELECT
    EmployeeName,
    Department,
    Salary,
    VAR(Salary) OVER () AS OverallSalaryVariance,
    VAR(Salary) OVER (PARTITION BY Department) AS DepartmentSalaryVariance
FROM Employees;

See Also