SQL’s window function

SQL’s window functions are a potent tool that enables you to perform

SQL’s window functions allow calculations over related rows, defined by the OVER() clause that partitions and orders the result set.

Here’s a more detailed account of window functions:

SQL
SQL
SQL
CREATE TABLE employees ( 
    employee_id INT, 
    department VARCHAR(50), 
    employee_name VARCHAR(50), 
    salary DECIMAL(10, 2), 
    hire_date DATE 
)

INSERT INTO employees (employee_id, department, employee_name, salary, hire_date) 
/* (1, 'HR', 'Alice', 50000.00, '2022-03-15'), */
/* use above format to insert data for any other platform than oracle */
(1, 'HR', 'Alice', 50000.00, to_date('2022-03-15', 'YYYY-MM-DD')),
(2, 'HR', 'Bob', 52000.00, to_date('2021-07-10', 'YYYY-MM-DD')),
(3, 'HR', 'Carol', 48000.00, to_date('2023-01-20', 'YYYY-MM-DD')),
(4, 'IT', 'David', 60000.00, to_date('2022-05-05', 'YYYY-MM-DD')),
(5, 'IT', 'Emma', 65000.00, to_date('2023-02-18', 'YYYY-MM-DD')),
(6, 'Finance', 'Frank', 55000.00, to_date('2021-12-02', 'YYYY-MM-DD')),
(7, 'Finance', 'Grace', 58000.00, to_date('2022-08-30', 'YYYY-MM-DD'));
EMPLOYEE_IDDEPARTMENTEMPLOYEE_NAMESALARYHIRE_DATE
1HRAlice5000015-MAR-22
2HRBob5200010-JUL-21
3HRCarol4800020-JAN-23
4ITDavid6000005-MAY-22
5ITEmma6500018-FEB-23
6FinanceFrank5500002-DEC-21
7FinanceGrace5800030-AUG-22

1. PARTITION BY Clause:

The result set is divided into partitions or groups based on one or more columns using the PARTITION BY clause. The window function is applied independently within each partition.

For example:

SQL
SQL
SQL
SELECT
    department,
    employee_name,
    salary,
    AVG(salary) OVER (PARTITION BY department) AS avg_salary_per_dept
FROM employees;
DEPARTMENTEMPLOYEE_NAMESALARYAVG_SALARY_PER_DEPT
FinanceFrank5500056500
FinanceGrace5800056500
HRBob5200050000
HRCarol4800050000
HRAlice5000050000
ITEmma6500062500
ITDavid6000062500

In this query, each department is divided using PARTITION BY, and the AVG(salary) window function calculates the average salary of each department.

2. ORDER BY Clause:

The ORDER BY clause is crucial for functions that rely on row order within partitions, such as RANK(), LEAD(), and LAG().

SQL
SQL
SQL
SELECT
    department,
    employee_name,
    salary,
    RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees;
DEPARTMENTEMPLOYEE_NAMESALARYDEPT_RANK
FinanceGrace580001
FinanceFrank550002
HRBob520001
HRAlice500002
HRCarol480003
ITEmma650001
ITDavid600002

Within each department, this system ranks employees based on their salary in descending order.

3. Window Frame Clause (ROWS and RANGE):

The window frame clause lets you specify a range of rows in each partition on which the window function operates.
Two types are available: ROWS BETWEEN and RANGE BETWEEN.

Use physical row positions with ROWS BETWEEN and specify frame bounds with UNBOUNDED PRECEDING, CURRENT ROW, or UNBOUNDED FOLLOWING.

For example:

SQL
SQL
SQL
SELECT
    department,
    employee_name,
    salary,
SUM(salary) OVER (PARTITION BY department ORDER BY hire_date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_salary
FROM employees;
DEPARTMENTEMPLOYEE_NAMESALARYCUMULATIVE_SALARY
FinanceFrank5500055000
FinanceGrace58000113000
HRBob5200052000
HRAlice50000102000
HRCarol48000150000
ITDavid6000060000
ITEmma65000125000

This calculates the cumulative sum of salaries, ordered by hire date, for each department from the start of the partition to the current row.

RANGE BETWEEN operates on values within a window and is useful for non-integer data.

For example:

SQL
SQL
SQL
SELECT
    department,
    employee_name,
    salary,
SUM(salary) OVER (PARTITION BY department ORDER BY salary ASC RANGE BETWEEN 1000 PRECEDING AND 1000 FOLLOWING) AS salary_range_sum
DEPARTMENTEMPLOYEE_NAMESALARYSALARY_RANGE_SUM
FinanceFrank5500055000
FinanceGrace5800058000
HRCarol4800048000
HRAlice5000050000
HRBob5200052000
ITDavid6000060000
ITEmma6500065000

This query calculates the sum of salaries within each department for employees whose salaries fall within 1000 units of the current employee’s salary, based on the specified order.

4. Common Window Functions

Here are some common window functions:

4.1 RANK(), DENSE_RANK(), ROW_NUMBER():

Assign a rank, dense rank, or row number within each partition.

These functions are used to assign a rank, dense rank, or row number to each row within a window defined by the OVER() clause.

RANK() assigns a unique rank to each distinct row, and if two or more rows have the same values, they receive the same rank, and the next rank is skipped.

DENSE_RANK() also assigns a unique rank to each distinct row, but if two or more rows have the same values, they receive the same rank, and the next rank is not skipped.

ROW_NUMBER() assigns a unique row number to each row within the window, without regard to duplicate values.

Example:

SQL
SQL
SQL
SELECT
    employee_name,
    salary,
    RANK() OVER (ORDER BY salary DESC) AS rank,
    DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank,
    ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_number
FROM employees;
departmentemployee_namesalaryrankdense_rankrow_number
HRAlice50000221
HRBob52000112
HRCarol48000333
ITDavid60000221
ITEmma65000112
FinanceFrank55000221
FinanceGrace58000112

In this query, we rank employees by their salary in descending order, using all three functions.

4.2 LEAD() and LAG():

Access values from subsequent or preceding rows.

LEAD() and LAG() allow you to access values from subsequent or preceding rows within the result set.

LEAD(column, n) retrieves the value of column from the row that is n rows after the current row.

LAG(column, n) retrieves the value of column from the row that is n rows before the current row.

Example:

SQL
SQL
SQL
SELECT
    order_id,
    order_date,
    LEAD(order_date, 1) OVER (ORDER BY order_date) AS next_order_date,
    LAG(order_date, 1) OVER (ORDER BY order_date) AS previous_order_date
FROM orders;
departmentemployee_namesalarynext_salaryprevious_salary
HRAlice5000052000NULL
HRBob520004800050000
HRCarol48000NULL52000
ITDavid6000065000NULL
ITEmma65000NULL60000
FinanceFrank5500058000NULL
FinanceGrace58000NULL55000

This query retrieves the order date, as well as the next and previous order dates for each order.

4.3 SUM(), AVG(), MIN(), MAX():

Perform aggregate calculations over the window.

These aggregate functions can be used with the OVER() clause to perform calculations over a window of rows.

  • AVG(column) OVER (PARTITION BY partition_column) calculates the average of column within each partition.
  • MIN(column) OVER (PARTITION BY partition_column) finds the minimum value of column within each partition.
  • MAX(column) OVER (PARTITION BY partition_column) finds the maximum value of column within each partition.

Example:

SQL
SQL
SQL
SELECT
    department,
    employee_name,
    salary,
    SUM(salary) OVER (PARTITION BY department) AS total_salary_dept,
    AVG(salary) OVER (PARTITION BY department) AS avg_salary_dept
FROM employees;
departmentemployee_namesalarytotal_salary_deptavg_salary_dept
HRAlice5000015000050000
HRBob5200015000050000
HRCarol4800015000050000
ITDavid6000012500062500
ITEmma6500012500062500
FinanceFrank5500011300056500
FinanceGrace5800011300056500

In this query, we calculate the total and average salary within each department.

4.4 FIRST_VALUE() and LAST_VALUE():

Retrieve the first or last value within the window.

FIRST_VALUE(column) retrieves the first value of column within the window.

LAST_VALUE(column) retrieves the last value of column within the window.

Example:

SQL
SQL
SQL
SELECT
    department,
    employee_name,
    salary,
    FIRST_VALUE(salary) OVER (PARTITION BY department ORDER BY salary) AS lowest_salary,
    LAST_VALUE(salary) OVER (PARTITION BY department ORDER BY salary) AS highest_salary
FROM employees;
departmentemployee_namesalarylowest_salaryhighest_salary
HRAlice500004800052000
HRBob520004800052000
HRCarol480004800052000
ITDavid600006000065000
ITEmma650006000065000
FinanceFrank550005500058000
FinanceGrace580005500058000

Window functions are especially useful for complex analytical tasks, such as calculating moving averages, identifying trends, and ranking data within groups. They provide a powerful way to gain insights into your data with precise control over how calculations are performed within specific partitions and ordered rows.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • Hypothesis Testing: A Comprehensive Overview

    This article delves into the application of hypothesis testing across diverse domains

  • Versions of ANCOVA (Analysis Of Covariance) with python

    To perform ANCOVA (Analysis of Covariance) with a dataset that includes multiple types of variables, you’ll need to ensure your dependent variable is continuous, and you can include categorical variables as factors. Below is an example using the statsmodels library in Python: Mock Dataset Let’s create a dataset with a mix of variable types: Performing…

  • Python Variables

    How useful was this post? Click on a star to rate it! Submit Rating Average rating 0 / 5. Vote count: 0 No votes so far! Be the first to rate this post.

  • A/B Testing Quiz

    Complete the code by dragging and dropping the correct functions

  • Python Functions

    Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain. Defining a Function: In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses,…

  • Python Indexing: A Guide for Data Science Beginners

    Mastering indexing will significantly boost your data manipulation and analysis skills, a crucial step in your data science journey.

  • Diffusion Models: Making AI Creativity

    Stable Diffusion Models: Where Art and AI Collide Artificial Intelligence meets creativity in the fascinating realm of Stable Diffusion Models. These innovative models take text descriptions and bring them to life in the form of detailed and realistic images. Let’s embark on a journey to understand the magic behind Stable Diffusion in a way that’s…

  • Quiz Challenge: Basics with Python [Questions]

    Solve These Questions in Following Challange

  • Introducing Plethora of Stable Diffusion models: Part 1

    Generate AI images as good as DALL-E completely offline.

One response to “SQL’s window function”

Points You Earned

Untitled design 6
0 distinction_points
Untitled design 5
python_points 0
0 Solver points
Instagram
WhatsApp
error: Content is protected !!