Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
PL/SQL Functions
Next article icon

Window Functions in PL/SQL

Last Updated : 24 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Oracle PL/SQL, analyzing and managing complex data relationships often involves performing calculations across sets of rows. This is where window functions, sometimes referred to as "Analytic functions," come into play. They enable powerful data analysis, such as sales forecasting, time-series analysis, and ranking without modifying the underlying data structure.

In this article, we are going to discuss about working of "Window Functions in PL/SQL". We will go through various real-world use cases with some clear and concise examples.

Window Functions in Oracle PL/SQL

A Windows function in Oracle PL/SQL performs aggregate operations, ranking functions, and analytic functions on groups of rows, but they will produce a result for each row. We will use two main clauses that will help our window function to perform operations:

  • OVER(): This clause will construct a window.
  • PARTITION BY: This will form rows into groups of rows.

We will also use the ORDER BY clause inside OVER() to arrange the resultant data into a specific order.

Syntax:

DECLARE --declare any variables here (if required)  BEGIN     FOR  i IN (         SELECT coulmn_name(s),          window_function(cloumn_01)        OVER([PARTITION BY column_01] [ORDER BY column_02]) AS dummy_column        FROM table_name;              ) LOOP         DBMS_OUTPUT.PUT_LINE('Display the Message Here');     END LOOP; END;

window function: aggregate or ranking function (like AVG() or ROW_NUMBER() )

Setting Up the Environment for Window Functions

To understand Window Functions in PL/SQL we need a table on which we will perform various operations and queries. Here we will consider a collection called geeksforgeeks which contains information such as emp_id, name department, that, and salary as Columns.

EMP_IDNAMEDEPARTMENTSALARY
108VishuIT60000
209AyushHR56000
110SumitIT54000
208NirajHR56000
109VivekIT65000
210HarshHR62000

1. Aggregate Window Function in Oracle PL/SQL

Aggregate window functions allow you to perform calculations like SUM, AVG, MAX, MIN, and COUNT over a specified window of rows. The functions that perform calculations like sum and average across the rows in our table are related to the current row.

  1. SUM(): Returns the total value for a column without our present window.
  2. AVG(): Returns the average value of a column within our present window.
  3. COUNT(): Returns the total number of rows within our present window.
  4. MAX(): Returns the maximum value in our present windows.
  5. MIN(): Returns the minimum value in our present windows.

Example of Aggregate Window Functions in PL/SQL

In this example, we will calculate the average salary, maximum salary, and minimum salary for our table 'geeksforgeeks'. We will calculate all the values separately for each department.

Query:

DECLARE BEGIN     DBMS_OUTPUT.PUT_LINE('EMP_ID   | Name    | Department  | Salary | Avg_Salary | Max_Salary | Min_Salary ');     DBMS_OUTPUT.PUT_LINE('------------------------------------------------------------------------------');     FOR i IN (         SELECT emp_id, name, department, salary,                AVG(salary) OVER (PARTITION BY department ) AS avg_sal,                MAX(salary) OVER (PARTITION BY department ) AS max_sal,                MIN(salary) OVER (PARTITION BY department ) AS min_sal         FROM geeksforgeeks     ) LOOP      DBMS_OUTPUT.PUT_LINE(i.emp_id || '      | ' || i.name || '   |   ' || i.department || '         | ' || i.salary||' |   '||CEIL(i.avg_sal)||'    |   '||i.max_sal||'    |   '||i.min_sal); END LOOP; END;

Output:

EMP_IDNameDepartmentSalaryAvg_SalaryMax_SalaryMin_Salary
209AyushHR56000580006200056000
208NirajHR56000580006200056000
210HarshHR62000580006200056000
109VivekIT65000596676500054000
108VishuIT60000596676500054000
110SumitIT54000596676500054000

Explanation: In the above query, we have performed average, max, and min for the salary column. In this query, our window functions are AVG(), MAX(), and MIN(). We have also used partition by function to separate different departments. We can see that for each department average, maximum, and minimum salaries are the same. You can refer to the above-shown image for more clear understanding.

2. Ranking Window Functions in Oracle PL/SQL

Ranking functions like ROW_NUMBER, RANK, and DENSE_RANK assign ranks to rows within a partition. These functions can be used for ordering and ranking employees based on salary.

This function assigns a specific rank to each row based on some internal criteria.

  1. ROW_NUMBER(): Assigns a unique integer id to each row within a partition.
  2. RANK(): Assigns a unique integer to each value within a partition. If two rows have the same value for our specified column then they will have the same rank. It will also create gaps when they are tied.
  3. DENSE_RANK(): It is similar to rank but it will not create gaps for the ties.

Example of Ranking Window Functions in PL/SQL

In this example, we will compute row number, rank, and dense rank for each row within a partition. We will see the working of the above functions as window functions.

Query:

DECLARE     CURSOR gfg_deatils IS         SELECT emp_id, name, department, salary,                ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary ) AS row_num,                RANK() OVER (PARTITION BY department ORDER BY salary ) AS rank,                DENSE_RANK() OVER (PARTITION BY department ORDER BY salary ) AS dense         FROM geeksforgeeks; BEGIN     DBMS_OUTPUT.PUT_LINE('EMP_ID   | Name    | Department  | Salary | Row_Number | Rank   | Dense_Rank ');     DBMS_OUTPUT.PUT_LINE('-----------------------------------------------------------------------------');     FOR i IN gfg_deatils LOOP         DBMS_OUTPUT.PUT_LINE(i.emp_id || '      | ' || i.name || '   |   ' || i.department || '         | ' || i.salary||' |   '||i.row_num||'        |   '||i.rank||'    |   '||i.dense);     END LOOP; END;

Output:

EMP_IDNameDepartmentSalaryRow_NumberRankDense_Rank
208NirajHR56000111
209AyushHR56000211
210HarshHR62000332
110SumitIT54000111
108VishuIT60000222
109VivekIT65000333

Explanation: As explained earlier, we can see that row numbers are unique for each row in a partition. The ranks are the same for the same salaries and it also leaves a gap when two ranks are the same. The dense ranks are also the same for the same salaries but it does not leave a gap unlike in rank. We can see that for id 210 rank is 3 and the dense rank is 2. The query is very similar to the previous one. You can refer to the image for more detailed understanding.

3. Analytic Window Functions in Oracle PL/SQL

In the analytic window function in PL/SQL, we will cover two main functions i.e. LEAD() and LAG().

  1. LEAD(): It returns the value from the row that precedes the current row within the same partition.
  2. LAG(): It returns the value from the row that succeeds the current row within the same partition.

Example of Analytic Window Functions in PL/SQL

In this example, we will calculate the preceding and succeeding salary for each row. If there are no preceding or succeeding salaries, then we will simply display the empty space.

Query:

DECLARE     CURSOR gfg_deatils IS         SELECT emp_id, name, department, salary,                LEAD(salary) OVER (PARTITION BY department ORDER BY salary ) AS lead_salary,                LAG(salary) OVER (PARTITION BY department ORDER BY salary ) AS lag_salary         FROM geeksforgeeks; BEGIN     FOR i IN gfg_deatils LOOP         DBMS_OUTPUT.PUT_LINE('Employee ID: ' || i.emp_id || ' Name: '||i.name||', Department: ' || i.department || ', Salary: ' || i.salary || ', Lead Salary: ' || i.lead_salary || ', Lag Salary: ' || i.lag_salary);     END LOOP; END;

Output:

Employee IDNameDepartmentSalaryLead SalaryLag Salary
208NirajHR5600056000NULL
209AyushHR560006200056000
210HarshHR62000NULL56000
110SumitIT5400060000NULL
108VishuIT600006500054000
109VivekIT65000NULL60000

Explanation: In the above image, we can see that all the rows are displayed with their corresponding preceding and succeeding salaries. We can also notice that the rows that do not have any preceding and succeeding salaries are empty like in id's 210 and 109 preceding salaries are absent and similar for id's 208, 110 succeeding salaries are absent. You can refer to the image for more clear understanding.

Important Points About PL/SQL Window Functions

  • Unlike aggregate functions, window functions return a value for each row, performing calculations across a set of rows related to the current row, without reducing the number of rows in the output.
  • The OVER() clause is mandatory for window functions. It defines the window (set of rows) over which the function operates.
  • If neither PARTITION BY nor ORDER BY is specified inside OVER(), the window function will consider all rows as a single partition, which may not be the intended behavior.
  • Window functions cannot be used directly in the WHERE clause. Instead, use them in a subquery or a common table expression (CTE).

Next Article
PL/SQL Functions

V

vishuvaishnav3001
Improve
Article Tags :
  • Databases
  • PL/SQL

Similar Reads

  • Window Functions in SQL
    SQL window functions are essential for advanced data analysis and database management. They enable calculations across a specific set of rows, known as a "window," while retaining the individual rows in the dataset. Unlike traditional aggregate functions that summarize data for the entire group, win
    7 min read
  • MySQL Window Functions
    MySQL Window Functions are advanced SQL capabilities that enable expensive calculations across sets of rows related to the current row. Aggregate functions collapse the result set. These functions, in general, permit ranking, running totals, moving averages, and access to data from other rows within
    6 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 o
    4 min read
  • Postgre Window Functions
    PostgreSQL is an advanced relational database management system, popular for its ability to handle both SQL (structured) and JSON (non-relational) queries. One of its most powerful features is window functions, which allow for complex data analysis across rows without collapsing data into a single r
    6 min read
  • Math Functions in PL/SQL
    In PL/SQL, mathematical functions play a important role in performing calculations and manipulating numeric data. These functions allow us to execute a wide range of mathematical operations from basic arithmetic to complex computations within our PL/SQL code. In this article, we will learn about Mat
    4 min read
  • Statistical Functions in PL/SQL
    PL/SQL provides powerful statistical functions to perform various statistical calculations directly within the Oracle database. It provides a rich set of statistical functions that allow developers to perform complex calculations without the need for external tools. These functions, such as AVG, STD
    5 min read
  • PL/SQL MAX() Function
    The PL/SQL MAX() function is an essential aggregate function in Oracle databases, enabling users to efficiently determine the largest value in a dataset. Whether working with numerical data, dates, or strings, the MAX() function is flexible and widely applicable. In this article, we will provide a d
    4 min read
  • PL/SQL SUM() Function
    The SUM() function in PL/SQL is used to calculate the sum of the numeric column. It is an aggregate function that performs calculations on a set of values and returns a single value. In this article, we will explore the syntax, usage, and examples of the PL/SQL SUM() function to help us understand i
    5 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 exampl
    5 min read
  • PLSQL | SQRT Function
    In PL/SQL, the SQRT function is used to find the square root of a number. This function is really handy for various tasks that involve mathematical calculations, such as analyzing statistics, solving geometry problems, or handling financial data. The SQRT function is easy to use and can simplify com
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences