EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials SQL Tutorial SQL Window Functions
Secondary Sidebar
SQL Tutorial
  • Functions
    • SQL Date Function
    • SQL Server Functions
    • SQL String Functions
    • SQL Compare String
    • Timestamp to Date in SQL
    • SQL REGEX
    • SQL Window Functions
    • SQL Syntax
    • SQL CONCAT
    • SQL ALTER TABLE
    • SQL MOD()
    • SQL Timestamp
    • SQL Min and Max
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite? functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Ranking Function
    • SQL Server Permission
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • SQL Quick References
    • SQL Like Wildcard
    • SQL Like with Multiple Values
    • SQL Examples
    • SQL Server Versions
    • SQL DROP DB
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL SELECT DISTINCT Multiple Columns
    • SQL Null Values
    • SQL LIKE
    • SQL LIKE Query
    • SQL LIKE Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • GROUP BY clause in SQL
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DESC
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • SQL Foreign Key
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • SQL UNIQUE Constraint
    • SQL Primary Key
    • Alternate Key in SQL
    • SQL Super Key
  • T-SQL
    • T-SQL pivot
    • T-SQL Formatter
    • T-SQL TRY CATCH
    • T-SQL CTE
    • T-SQL CASE
    • T-SQL DATEPART
    • T-SQL Date Format
    • T-SQL ROUND
    • T-SQL Loop
    • T-SQL IIF
    • T-SQL Union
    • T-SQL CREATE TABLE
    • T-SQL INSERT
    • T-SQL Stuff
    • T-SQL ISNULL
    • T-SQL ADD Column
    • T-SQL DATEDIFF
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • LEFT OUTER JOIN in SQL
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • SQL Aliases
    • SQL Hosting
    • SQL Auto Increment
    • SQL Injection
    • SQL Wildcards
    • SQL Check
    • SQL Indexes
    • Select Distinct
    • SQL BETWEEN
    • SQLPlus spool
    • SQL Create Table
    • SQL Schema
    • Comparison Operators in SQL
    • SQL_plus
    • SQL Formatter
    • SQL LEFT INNER JOIN
    • SQL Plus Command
    • SQLPlus not found
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • SQL REVOKE
    • SQL Select Distinct Count
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • SQL DROP Table
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • SqlAlchemy
    • What is SQLAlchemy
    • SqlAlchemy ORM
    • SQLAlchemy count
    • SQLAlchemy update object
    • SQLAlchemy pip
    • SQLAlchemy Connection
    • SQLAlchemy Metadata
    • SQLAlchemy Raw SQL
    • SQLAlchemy Filter in List
    • SQLAlchemy Alias
    • SQLAlchemy unique
    • SQLAlchemy JSONB
    • SQLAlchemy Async
    • SQLAlchemy Types
    • SQLAlchemy Many to Many
    • SQLAlchemy Example
    • SQLAlchemy Model
    • SQLAlchemy Data Types
    • SQLAlchemy Filter
    • SQLAlchemy SQLite
    • SQLAlchemy DateTime
    • SQLAlchemy create_engine
    • SQLAlchemy Delete
    • SQLAlchemy Migrations
  • NoSQL
    • NoSQL Databases List
    • NoSQL Data Modeling
    • Types of NoSQL Databases
    • NoSQL Injection
    • NoSQL vs SQL Databases
    • NoSQL Use Cases
    • NoSQL Key Value
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions
    • SQL Current Month

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

SQL Window Functions

By Ravi KhatriRavi Khatri

SQL Window Functions

Introduction to SQL Window Functions

The following article provides an outline for SQL Window Functions. A window function gets out an estimation over a lot of table rows that are by one way or another identified with the present line. This is somehow related to aggregate functions which we are used to but unlike aggregate functions, window functions do not group the result into single row but each row have its separate identity. So,more than just the current row of the query result is accessed by the window function. This provide extremely powerful and useful features, but since they are different from the standard SQL, they are difficult to grasp and have strange syntax and are very often avoided.

There are different classes of window functions:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,112 ratings)
  • Aggregate functions: COUNT, AVG, SUM, MAX, MIN, etc.
  • Ranking functions: RANK, ROW_NUMBER, DENSE_RANK etc.
  • Analytic functions: FIRST_VALUE, LAST_VALUE, LEAD, LAG etc.

The partitioning and order of rows is defined by OVER clause in a window and so they are called window function and following arguments are used in this clause:

  • ORDER BY: It defines the logical order of the rows.
  • PARTITION BY: It divides the result into separate partitions and the window function is applied individually to every partition.
  • ROWS or RANGE clause: It limits the rows within the partition by specifying start and end points within the partition.

If ROWS or RANGE clause is not specified then the default value is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

Examples of SQL Window Functions

Given below are the examples mentioned:

Example #1

Simple example with AVG() function.

Code:

SELECT emp_name, emp_gender, emp_salary,
AVG(emp_salary) OVER (ORDER BY emp_salary) AS CalAverage
from Employee;

Output:

SQL Window Functions 1

Explanation:

  • This is the most basic example in which we select name, gender and salary from Employee table and used AVG function to get the salary of employee. As you can see average of Mark is 1000 and that of John is 1500. Since we have not used ROWS and RANGE clause all the rows before the current row are considered in the average.
  • In other words, the average is taken between unbounded preceding and the current row. Similarly, all other values are calculated. Notice the last row has the true average because it calculates all the rows above it.

Example #2

Using ROWS or RANGE clause.

Code:

SELECT emp_name, emp_gender, emp_salary,
AVG(emp_salary)OVER (ORDER BY emp_salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CalAverage,
SUM(emp_salary)OVER (ORDER BY emp_salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CalSum,
COUNT(emp_salary)OVER (ORDER BY emp_salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CalCount
from Employee;

Output:

SQL Window Functions 2

Explanation:

  • In this example we select name, gender and salary from Employee table and used AVG, SUM, COUNT function to do some calculation and as you can see the aggregate functions are working on the entire result set which gives us same values and there are two reason for this.
  • First is that we are using ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING which gives us values of entire result and second is we are not using PARTITION so the entire result is considered one partition and so we are getting same result.

Example #3

Using PARTITION clause.

Code:

SELECT emp_name, emp_gender, emp_salary,
AVG (emp_salary) OVER (PARTITION BY emp_gender ORDER BY emp_salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CalAverage,
SUM (emp_salary) OVER (PARTITION BY emp_gender ORDER BY emp_salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CalSum,
COUNT (emp_salary) OVER (PARTITION BY emp_gender ORDER BY emp_salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CalCount
from Employee;

Output:

SQL Window Functions 3

Explanation:

  • This is same as above example, the only difference is that in this we have used PARTITION BY clause to partition the data by gender, so the windows functions are applied within the partition and the average, sum and count is calculated accordingly.

Example #4

One preceding row and one following row.

Code:

SELECT emp_name, emp_gender, emp_salary,
AVG (emp_salary) OVER (ORDER BY emp_salary ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS CalAverage,
SUM (emp_salary) OVER (ORDER BY emp_salary ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS CalSum,
COUNT (emp_salary) OVER (ORDER BY emp_salary ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS CalCount from Employee;

Output:

One preceding row and one following row

Explanation:

  • In this query example we have calculated the salary of current row, one row preceding and one row following. So, the average of Mark is 1500 as it has no preceding row but only following row.
  • Similarly, John average is same 2000 because it has one preceding row and one following row.

Example #5

Simple example with LEAD() function.

Code:

SELECT emp_name, emp_gender, emp_salary,
LEAD (emp_salary) OVER (ORDER BY emp_salary)as Lead
FROM Employee;

Output:

LEAD()

The following shows the common syntax of a LEAD() in SQL Server:

LEAD(return_value ,offset [,default])
OVER (
[PARTITION BY partition_expression, ... ] ORDER BY sort_expression [ASC or DESC], ...
)

Explanation:

  • This is the most basic example in which we select name, gender and salary from Employee table and used LEAD function to get the salary of next person.
  • As you can see Ron get NULL because there is no next salary and also, we have not specified any default value and offset is 1 so we get the immediate previous value.

Example #6

A bit complex example with LEAD() function.

Code:

SELECT emp_name, emp_gender, emp_salary,
LEAD (emp_salary, 2,-1) OVER (PARTITION BY emp_gender ORDER BY emp_salary) AS Lead
FROM Employee;

Output:

bit complex example with LEAD()

Explanation:

  • In this example we select name, gender and salary from Employee table and used LEAD function to get the salary of next person in Lead column as done in previous example but also, we partition the data using gender column. So, the LEAD function works within the confines of the partition.
  • What we have done is we have set the offset to 2 and default value to -1. As we can see in the example for Mary and Jodi we cannot fetch the values of next rows which is leads 2 rows so we get the default value -1 and similarly in the Male partition we get the result.

Conclusion

Now you know what window functions are in SQL server and how it is used to calculate results from multiple rows without grouping.

Recommended Articles

This is a guide to SQL Window Functions. Here we discuss the introduction to SQL Window Functions along with examples for better understanding. You may also have a look at the following articles to learn more –

  1. Array in SQL
  2. SQL Bulk Insert
  3. Azure SQL Database
  4. SQL While Loop
Popular Course in this category
SQL Training Program (7 Courses, 8+ Projects)
  7 Online Courses |  8 Hands-on Projects |  73+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

JDBC Training (6 Courses, 7+ Projects)4.9
PHP Training (5 Courses, 3 Project)4.8
Windows 10 Training (4 Courses, 4+ Projects)4.7
PL SQL Training (4 Courses, 2+ Projects)4.7
Oracle Training (14 Courses, 8+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more