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:
PostgreSQL- LPAD Function
Next article icon

PostgreSQL – LAG Function

Last Updated : 01 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In PostgreSQL, the LAG() function is a powerful window function that allows you to access data from a previous row within the same result set. It’s particularly useful for comparing values in the current row with values in the preceding row, making it ideal for analytical queries in PostgreSQL.

For example, we can use LAG() to analyze trends, such as comparing sales data over different time periods. In this article, we will explain how to use the PostgreSQL LAG function, starting with the syntax and practical Examples.

What is PostgreSQL LAG Function ?

The LAG() function operates on partitions created by the PARTITION BY clause. If no partition is specified, the function treats the entire result set as a single partition. The ORDER BY clause determines the order of rows within each partition to which the LAG() function is applied. The LAG() function is a window function that retrieves the value of a column from a prior row in the same partition, based on a specified offset. If the offset extends beyond the start of the partition, a default value can be returned, preventing null results in the analysis.

Syntax

LAG(expression [, offset [, default_value]]) 
OVER (
[PARTITION BY partition_expression, ... ]
ORDER BY sort_expression [ASC | DESC], ...
)

Key Terms:

  • expression: This sets the basis for the comparison between the current row and the row at the specified offset. It can be a column, an expression, or a subquery.
  • offset: A positive integer specifying the number of rows before the current row. If not specified, it defaults to 1.
  • default_value: This value is returned if the offset goes beyond the scope of the partition.

Examples of the PostgreSQL LAG() Function

Below are some practical examples that demonstrate how the LAG() function works in PostgreSQL, with each example showcasing a unique use case.

Example 1: Comparing Current Year Sales with Previous Year Sales

Suppose we have a table named sales that tracks sales for different years and product groups. Here’s the structure. Let’s set up a new table for the demonstration named ‘sales‘:

Query:

CREATE TABLE sales(
year SMALLINT CHECK(year > 0),
group_id INT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
PRIMARY KEY(year, group_id)
);

Insert some data into the ‘sales' table:

INSERT INTO sales (year, group_id, amount) 
VALUES
(2018, 1, 1474),
(2018, 2, 1787),
(2018, 3, 1760),
(2019, 1, 1915),
(2019, 2, 1911),
(2019, 3, 1118),
(2020, 1, 1646),
(2020, 2, 1975),
(2020, 3, 1516);

To use the LAG() function to return the sales amount of the current year and the previous year, you can write the following query:

WITH cte AS (
SELECT
year,
SUM(amount) AS amount
FROM sales
GROUP BY year
)
SELECT
year,
amount,
LAG(amount, 1) OVER (ORDER BY year) AS last_year_sales
FROM cte;

Output

Example 1: Output

Explanation:

  • The LAG(amount, 1) retrieves the amount from the previous row.
  • ORDER BY year ensures that the comparison is made by year in ascending order.

Example 2: Comparing Sales of Current Year with Previous Year for Each Product Group

This example uses the LAG() function to compare the sales of the current year with the sales of the previous year of each product group:

Query:

SELECT
year,
amount,
group_id,
LAG(amount, 1) OVER (
PARTITION BY group_id
ORDER BY year
) AS last_year_sales
FROM sales;

Output

Example 2: Output

Explanation:

  • Here, PARTITION BY group_id divides the data by group_id, ensuring that LAG() operates separately within each product group.
  • ORDER BY year orders rows within each product group, enabling comparison by year.

Important Points About LAG() Function in PostgreSQL

  • The LAG() function is used to compare the values of the current row with the previous row within a specified window of rows.
  • The LAG() function is a window function, meaning it operates over a set of table rows that are somehow related to the current row.
  • Similar to the LEAD() function, which accesses data from rows that come after the current row, LAG() function accesses data from rows before the current row.
  • By using the PARTITION BY clause, you can divide the result set into partitions and apply the LAG() function to each partition independently.
  • The ORDER BY clause specifies the order of rows within each partition to which the LAG() function is applied.

Conclusion

The LAG() function in PostgreSQL is essential for data comparison within ordered datasets, providing analysts and developers with a means to retrieve prior row values. Whether we are working with financial data, inventory levels, or time-based analysis, the LAG() function offers a structured way to view relationships in sequential data. By Using PARTITION BY and ORDER BY clauses, you can use LAG() across distinct groups, gaining insights into historical trends and performance over time.



Next Article
PostgreSQL- LPAD Function

R

RajuKumar19
Improve
Article Tags :
  • Databases
  • PostgreSQL
  • PostgreSQL-function
  • PostgreSQL-Window-function

Similar Reads

  • PostgreSQL - LEAD Function
    In PostgreSQL, the LEAD() function is a powerful window function used to access a row that follows the current row at a specific physical offset. This function is generally employed to compare the value of the current row with the value of the next row following the current row. Let us better unders
    3 min read
  • PostgreSQL- LPAD Function
    The LPAD() function in PostgreSQL is a powerful tool for padding a string to the left, ensuring it reaches a specified length by filling it with a designated character or characters. This function can be particularly useful in data formatting and report generation. Let us better understand the LPAD
    2 min read
  • PostgreSQL - MAX() Function
    The MAX() function in PostgreSQL is a versatile and powerful aggregate function used to determine the maximum value within a set of values. It plays a crucial role in data analysis, reporting, and SQL query optimization. This function can be applied in SELECT, WHERE, GROUP BY, and HAVING clauses, ma
    4 min read
  • PostgreSQL - NTILE() Function
    In PostgreSQL, the NTILE() function is a powerful tool used to divide ordered rows into a specified number of ranked buckets, which are essentially ranked groups. This function is crucial for data analysis and reporting, allowing users to efficiently distribute rows and analyze data in a structured
    3 min read
  • PostgreSQL - NOW() Function
    The NOW() function in PostgreSQL is a powerful and essential tool for retrieving the current date and time. This is particularly useful when recording actions like adding or updating records in our database. Using PostgreSQL NOW() function, we can efficiently track when events occur, making the data
    4 min read
  • PostgreSQL MIN() Function
    The MIN() function in PostgreSQL is an essential aggregate function that returns the minimum value in a set of values. This function is highly useful in various data analysis and reporting tasks, allowing you to quickly identify the smallest values in your datasets. Let us better understand the MIN(
    2 min read
  • PostgreSQL - MD5() Function
    The PostgreSQL MD5() function is a useful tool for evaluating the MD5 hash of a given string and returning the result in hexadecimal form. This function is often used for data integrity checks and secure password storage. Let's look into the syntax, and usage of the MD5() function in PostgreSQL with
    2 min read
  • PostgreSQL - NULLIF() Function
    Effectively handling NULL values is important in database management, especially for ensuring data integrity and avoiding errors. PostgreSQL offers several powerful functions, such as NULLIF and COALESCE, to help manage NULL and empty values efficiently. In this article, we will guide us through the
    4 min read
  • PostgreSQL - Function Overloading
    In PostgreSQL, it's possible to create multiple functions with the same name, provided that each function has different arguments. This feature, known as function overloading, allows you to define functions that perform similar operations but handle different types or numbers of inputs. PostgreSQL d
    3 min read
  • PostgreSQL - AGE Function
    In PostgreSQL, the AGE() function is a powerful tool for calculating the difference between two TIMESTAMP values. This function is especially useful for determining the age of individuals or the duration between events. Let us better understand the AGE() Function in PostgreSQL from this article. Syn
    2 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