The Wayback Machine - https://web.archive.org/web/20240906173639/https://www.geeksforgeeks.org/sql-statistical-functions/
Open In App

SQL – Statistical Functions

Last Updated : 04 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

SQL statistical functions are essential tools for extracting meaningful insights from databases. These functions, such as AVG(), SUM(), COUNT(), MIN(), MAX(), STDDEV(), and VAR(), enable users to perform statistical calculations on numeric data. Whether determining averages, sums, counts, or measures of variability, these functions empower efficient data analysis within the SQL environment.

What is Statistics?

So, Statistics is a branch of mathematics that deals with data collection, analysis, interpretation, presentation, and organization. It involves the use of mathematical techniques to extract meaningful information from data. Statistics is widely used in various fields such as business, economics, social science, medicine, and engineering

Where do We Use Stats?

let’s define Statistical Function, A Statistical function is a mathematical function that helps us to process and analyze data to provide meaningful information about the dataset. For example mean, sum, min, max, standard deviation, etc.

Statistical Functions in SQL

Here are Some Common Statistical Functions in SQL:

Function

Output

AVG()

Calculates the average value of a numeric column.

SUM()

Calculates the sum of values in a numeric column.

COUNT()

Counts the number of rows in a result set or the number of non-null values in a column.

MIN()

Returns the minimum value in a column.

MAX()

Returns the maximum value in a column.

VAR() / VARIANCE()

Calculates the population variance of a numeric column.

STDDEV() / STDDEV_POP()

Calculates the population standard deviation of a numeric column.

CORR()

Calculates the correlation coefficient between two numeric columns.

COVAR_POP()

Calculates the population covariance between two numeric columns.

PERCENTILE_CONT()

Calculates a specified percentile value for a numeric column

Statistical Functions With Exmaple

We have four tables in our database: ‘studentDetails,’ ’employees,’ ‘sales_data,’ and ‘financial_data.’ (The pictures are displayed below.)

StudentDetails

Table : StudentDetails

employees Table:

Employeetable

Table:Employees

sales_data:

Table_sale_data

Table:Sales_data

financial_data:

Table_finance

Table: financial_data

1. AVG() Function

Calculate the average or arithmetic mean for a group of numbers or a numeric column.

Syntax:

SELECT AVG(column_name) FROM table_name;

Example Query:

SELECT AVG(marks) AS average_marks FROM studentDetails;

Output:

AVG()

AVG_MARKS

2. SUM() Function

The total of all numeric values in a group i.e. Calculates the total sum of values in a numeric column.

Syntax:

SELECT SUM(column_name) FROM table_name;

Example Query:

SELECT SUM(marks) AS total_marks FROM studentDetails;

Output:

SUM()

Sum of marks

3. Count() Function

The number of cell locations in a range that contain a numeric character i.e Counts the number of rows in a result set or the number of non-null values in a column.

Syntax:

SELECT COUNT(*) FROM table_name;

SELECT COUNT(column_name) FROM table_name;

Example Query:

SELECT COUNT(studentID) AS total_students FROM studentDetails;

Output:

COUNT()

Count of Student

Example Query:

select count(*) from studentdetails;

Output:

Return the count of rows that meet a specified condition .

countAll

count all rows

4. Max() Function

Returns the highest numeric value in a group of numbers.

Syntax:

SELECT MAX(column_name) FROM table_name;

Example Query:

SELECT MAX(marks) AS highest_marks FROM studentDetails;

Output:

MAX()

Maximum marks

5. MIN() Function

Returns the lowest numeric value in a group of numbers.

Syntax:

SELECT MIN(column_name) FROM table_name;

Example Query:

SELECT MIN(marks) AS lowest_marks FROM studentDetails;

Output:

MIN()

Minimum marks

6. VAR() / VARIANCE() Function

Calculates the population variance of a numeric column

Syntax:

SELECT VAR(column_name) FROM table_name;

Example Query:

SELECT VARIANCE(marks) AS variance_marks FROM studentDetails;

Output:

VAR()

Variance marks

7. STDDEV() / STDDEV_POP() Function

The standard deviation for a group of numbers based on a sample

Syntax:

SELECT STDDEV(column_name) FROM table_name;

Example Query:

SELECT STDDEV(marks) AS stddev_marks FROM studentDetails;

Output:

STDDEV()

Standrad deviation for marks

8. PERCENTILE_CONT() Function

Calculates a specified percentile value for a numeric column.

Syntax:

SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY column_name) FROM table_name;

Example Query:

SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees;

Output:

percentail()

Median salary of employee’s

9. CORR() Function

Calculates the correlation coefficient between two numeric columns.

Syntax:

SELECT CORR(column1, column2) FROM table_name;

Example Query:

SELECT CORR(sales, profit) AS correlation_coefficient
FROM sales_data;

Output:

Corr()

correlation coefficient between ‘sales’ and ‘profit’

10 .COVAR_POP() Function

Calculates the population covariance between two numeric columns.

Syntax:

SELECT COVAR_POP(column1, column2) FROM table_name;

Example Query:

SELECT COVAR_POP(revenue, expenses) AS population_covariance
FROM financial_data;

Output:

covarrPOP()

Population Covariance between revenue and expenses

Conclusion

In SQL, statistical functions help to analyze and summarise data in the database. These functions assist in extracting meaningful information from the given datasets. For determining the number of occurrences , calculating totals , finding averages or calculating the variance in the dataset statistical functions plays a vital role .Overall, the integration of Statistical Functions elevates SQL’s capabilities, making it an invaluable asset for businesses and analysts seeking actionable intelligence from their relational databases.



Previous Article
Next Article

Similar Reads

MySQL Statistical Functions
MySQL provides a rich set of statistical functions that we can use to perform various statistical analyses directly within the database. These functions help us to derive insights and trends from large datasets and are essential for data analysis. This article will explore some of the key MySQL statistical functions. What are Statistical Functions?
4 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
Functions in MySQL | Numeric, String and Date Time Functions in MySQL
MySQL functions are powerful tools that help in performing complex calculations and data manipulation with ease. The functions in MySQL can edit rows and tables, alter strings, and help you manage organized and easy-to-navigate databases. A function is a special type of predefined command set that performs some operation and returns a value. Functi
3 min read
SQL | Numeric Functions
Numeric Functions are used to perform operations on numbers and return numbers. Following are the numeric functions defined in SQL: ABS(): It returns the absolute value of a number. Syntax: SELECT ABS(-243.5); Output: 243.5 SQL> SELECT ABS(-10); +--------------------------------------+ | ABS(10) +--------------------------------------+ | 10 +---
3 min read
SQL | Advanced Functions
SQL (Structured Query Language) offers a wide range of advanced functions that allow you to perform complex calculations, transformations, and aggregations on your data. Aggregate Functions In database management an aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single
2 min read
Date manipulating functions in SQL
To manipulate and fetch date values from the table, oracle has inbuilt date functions. Here, we are going to cover Date manipulating functions in SQL. ADD_MONTHS : It will add the total number of months specified in n to the date parameter and Returns date. Syntax : ADD_MONTHS(d, n) Example - Select ADD_MONTHS(SYSDATE, 4) "Add months" from dual; Ou
2 min read
How to Use HAVING With Aggregate Functions in SQL?
SQL provides many built-in functions to perform tasks. There are 4 types of functions Date functions, Char functions, Numeric functions, and Aggregate functions. Here we will be looking at aggregate functions and how to use them with the HAVING keyword. Aggregate Functions are database built-in functions that act on multiple rows of the table and p
4 min read
How to Use SELECT With Aggregate Functions in SQL?
In SQL, mainly five aggregate functions are provided. These help us to process the table data in the desired way. All these are illustrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE Gee
2 min read
SQL Server Group Functions
The group function in SQL Server provides a powerful tool for performing calculations on groups of rows, allowing you to group data based on specific criteria. This function is important when you want to analyze and summarize information from multiple records in a data structure. The basic group functions are COUNT, SUM, AVG, MAX, and MIN. Syntax:
3 min read
SQL | NULL functions
In the database, null values serve as placeholders for data that is either missing or not available. a null value is a flexible data type that can be placed in the column of any data type, including string, int, blob, and CLOB datatypes. It is not a component of any specific data type. Null values are helpful when cleaning the data prior to explora
5 min read
SQL | Character Functions with Examples
Character functions accept character inputs and can return either characters or number values as output. SQL provides a number of different character datatypes which includes - CHAR, VARCHAR, VARCHAR2, LONG, RAW, and LONG RAW. The various datatypes are categorized into three different datatypes : VARCHAR2 - A variable-length character datatype whos
6 min read
SQL Server Window Functions ROWS vs. RANGE
We will cover the important concept of the MS SQL Server which is the difference between Row and Range. The confusion between the row and range and where it is used will be eradicated by reading this article. So, be with the flow of the article for a better understanding and keep practicing side by side. Understanding this topic will help you in be
5 min read
Window Functions in PL/SQL
A window function is sometimes referred to as an "Analytic Function". It is generally used to perform calculations on some specific set of rows related to each row in our result set. There are some real-world applications of the window function, they are sales analysis, inventory management, time series analysis, and so on. In short, the window fun
6 min read
How to Find the Length of a Series Using Window Functions in SQL
In data analysis, understanding the sequential patterns within datasets is crucial for informed decision-making. SQL's window functions offer a powerful toolset for such tasks, allowing efficient calculations across related rows. This article delves into utilizing window functions to determine the length of series within datasets. Beginning with an
5 min read
Date and Time Functions in PL/SQL
Date and Time Functions in PL/SQL are useful for date and time operations like extracting date components, performing date arithmetic, and converting between date formats. Date and Time Functions in PL/SQLThere are many useful Date and Time functions in PL/SQL. A table of such functions along with their description is given below: S.noFunctionDescr
4 min read
SQL MIN() and MAX() Functions
The SQL MIN() and MAX() functions are the aggregate functions in SQL, that operate on group of data and return one output. The SQL Min() function returns the minimum value of the selected columns, and the SQL MAX() function is used to return the maximum value of the selected columns. In this article, we will understand the concept of MIN() and MAX(
3 min read
Deterministic and Nondeterministic Functions in SQL Server
Deterministic and nondeterministic functions are two fundamental concepts in SQL Server that determine how a function behaves when called with a specific set of input values. Deterministic functions always return the same result every time they are called with a fixed set of input values and given the same state of the database. On the other hand,
2 min read
PL/SQL Functions
PL/SQL functions are reusable blocks of code that can be used to perform specific tasks. They are similar to procedures but must always return a value. A function in PL/SQL contains:Function Header: The function header includes the function name and an optional parameter list. It is the first part of the function and specifies the name and paramete
4 min read
SQL Server Mathematical Functions (SQRT, PI, SQUARE, ROUND, CEILING & FLOOR)
SQL Server mathematical functions are used to perform mathematical calculations. These functions are designed to simplify complex calculations and make it easier to analyze and manipulate data. Here, we will cover the syntax and examples of various mathematical functions like SQRT(), PI(), SQUARE(), and many more Mathematical Functions in SQL Serve
1 min read
SQL Date and Time Functions
In SQL, dates are complicated for newbies, since while working with a database, the format of the data in the table must be matched with the input data to insert. In various scenarios instead of date, datetime (time is also involved with date) is used. For storing a date or a date and time value in a database,MySQL offers the following data types:
3 min read
SQL Aggregate functions
SQL Aggregate functions are functions where the values of multiple rows are grouped as input on certain criteria to form a single value result of more significant meaning. It is used to summarize data, by combining multiple values to form a single result. SQL Aggregate functions are mostly used with the GROUP BY clause of the SELECT statement. Vari
2 min read
SQL | String functions
String functions are used to perform an operation on input string and return an output string. Following are the string functions defined in SQL: ASCII(): This function is used to find the ASCII value of a character. Syntax: SELECT ascii('t');Output: 116CHAR_LENGTH(): Doesn't work for SQL Server. Use LEN() for SQL Server. This function is used to f
4 min read
SQL General Functions
SQL general functions are built-in tools provided by SQL databases to perform a variety of operations on data. These functions are crucial for manipulating, analyzing, and transforming data efficiently. In this article, We will learn about the what are the SQL General Functions along with the examples and so on. SQL General FunctionsSQL general fun
5 min read
SQL | Date Functions (Set-1)
SQL Date Functions are essential for managing and manipulating date and time values in SQL databases. They provide tools to perform operations such as calculating date differences, retrieving current dates and times and formatting dates. In this article, We will learn about the various SQL Date Functions with the help of examples and so on. SQL Dat
5 min read
SQL | Date Functions (Set-2)
SQL Date Functions are powerful tools that allow users to manipulate, extract, and format date and time values within SQL databases. In this article, We will learn about What are SQL Date Functions along with various examples and so on. What are SQL Date Functions?SQL Date Functions are built-in functions that help manipulate, extract, and format d
4 min read
Window functions in SQL
Window functions apply to aggregate and ranking functions over a particular window (set of rows). OVER clause is used with window functions to define that window. OVER clause does two things : Partitions rows to form a set of rows. (PARTITION BY clause is used) Orders rows within those partitions into a particular order. (ORDER BY clause is used) N
4 min read
Categories of SQL Functions
SQL functions are powerful tools that help streamline queries, perform operations, and manipulate data efficiently. They are essential for handling various tasks within SQL queries and database management. Functions in SQL can be broadly categorized into predefined (built-in) functions and user-defined functions. In this article, We will learn abou
4 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read