{"id":1167,"date":"2024-12-21T22:30:12","date_gmt":"2024-12-21T15:30:12","guid":{"rendered":"https:\/\/www.pgtutorial.com\/?page_id=1167"},"modified":"2025-01-05T21:16:10","modified_gmt":"2025-01-05T14:16:10","slug":"postgresql-lag","status":"publish","type":"page","link":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/","title":{"rendered":"PostgreSQL LAG Window Function"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: In this tutorial, you&#8217;ll learn how to use the PostgreSQL <code>LAG<\/code> window function to compare the current row&#8217;s value with the previous row.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='getting-started-with-the-postgresql-lag-window-function'>Getting Started with the PostgreSQL LAG Window Function <a href=\"#getting-started-with-the-postgresql-lag-window-function\" class=\"anchor\" id=\"getting-started-with-the-postgresql-lag-window-function\" title=\"Anchor for Getting Started with the PostgreSQL LAG Window Function\">#<\/a><\/h2>\n\n\n\n<p>In PostgreSQL, the <code>LAG()<\/code> function allows you to access data of a previous row from the current row within the same partition.<\/p>\n\n\n\n<p>You often use the <code>LAG()<\/code> function to compare the current row&#8217;s value with the previous row, such as sales vs. previous year.<\/p>\n\n\n\n<p>Here&#8217;s the syntax of the PostgreSQL <code>LAG<\/code> window function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\">LAG(<span class=\"hljs-keyword\">value<\/span>&#91;, <span class=\"hljs-keyword\">offset<\/span> &#91;, <span class=\"hljs-keyword\">default<\/span>]]) <span class=\"hljs-keyword\">OVER<\/span> (\n    &#91;<span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> partition_expression]\n    &#91;<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> sort_expression]\n)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this syntax<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>value<\/code>: A column or expression that you want to return the value of the previous row.<\/li>\n\n\n\n<li><code>offset<\/code>: Specifies the number of rows back from the current row you want to retrieve the value. The offset defaults to 1, which accesses the previous row&#8217;s value.<\/li>\n\n\n\n<li><code>default<\/code>: This is the default value if the previous row does not exist. If you don&#8217;t specify a default value, the function returns <code>NULL<\/code> if the current row is the first row in the partition, which has no previous row.<\/li>\n\n\n\n<li><code>PARTITION BY<\/code>: Divides the result set into partitions by the <code>partition_expression<\/code>. If you omit the <code>PARTITION BY<\/code> clause, the <code>LAG<\/code> function treats the whole result set as a single partition.<\/li>\n\n\n\n<li><code>ORDER BY<\/code>: Determines the order of the rows within each partition.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='postgresql-lag-window-function-examples'>PostgreSQL LAG Window Function Examples <a href=\"#postgresql-lag-window-function-examples\" class=\"anchor\" id=\"postgresql-lag-window-function-examples\" title=\"Anchor for PostgreSQL LAG Window Function Examples\">#<\/a><\/h2>\n\n\n\n<p>Let&#8217;s explore some examples of using the <code>LAG<\/code> function with the <code>sales<\/code> table and <code>sales_by_years<\/code> view:<\/p>\n\n\n\n<p>The <code>sales<\/code> table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> * <span class=\"hljs-keyword\">FROM<\/span> sales;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=lag&amp;q=U0VMRUNUICogRlJPTSBzYWxlczs%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>The <code>sales_by_years<\/code> view:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> * <span class=\"hljs-keyword\">FROM<\/span> sales_by_years;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=lag&amp;q=U0VMRUNUICogRlJPTSBzYWxlc19ieV95ZWFyczs%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='using-postgresql-lag-to-compare-yearly-sales'>Using PostgreSQL LAG to Compare Yearly Sales <a href=\"#using-postgresql-lag-to-compare-yearly-sales\" class=\"anchor\" id=\"using-postgresql-lag-to-compare-yearly-sales\" title=\"Anchor for Using PostgreSQL LAG to Compare Yearly Sales\">#<\/a><\/h3>\n\n\n\n<p>The following <code>SELECT<\/code> statement uses the <code>LAG()<\/code> function to compare the sales amount of each year with the previous year in the <code>sales_by_years<\/code> view:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  year,\n  amount,\n  LAG(amount) <span class=\"hljs-keyword\">OVER<\/span> (\n    <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year\n  ) <span class=\"hljs-keyword\">AS<\/span> previous_year_amount\n<span class=\"hljs-keyword\">FROM<\/span>\n  sales_by_years;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=lag&amp;q=U0VMRUNUIHllYXIsIGFtb3VudCwgTEFHKGFtb3VudCkgT1ZFUiAoIE9SREVSIEJZIHllYXIgKSBBUyBwcmV2aW91c195ZWFyX2Ftb3VudCBGUk9NIHNhbGVzX2J5X3llYXJzOw%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\"> year |  amount   | previous_year_amount\n------+-----------+----------------------\n 2019 | 513700.00 |                 NULL\n 2020 | 490000.00 |            513700.00\n 2021 | 512000.00 |            490000.00\n 2022 | 483200.00 |            512000.00\n 2023 | 491000.00 |            483200.00<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>ORDER BY<\/code> clause sorts the rows of the result set by year in ascending order.<\/li>\n\n\n\n<li>The <code>LAG(amount)<\/code> function accesses the amount of the previous year. Note that offset defaults to 1. Since the first row (2019) has no previous row, the <code>LAG()<\/code> function returns <code>NULL<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id='calculating-sales-change-percentage-vs-previous-year'>Calculating Sales Change Percentage vs. Previous Year <a href=\"#calculating-sales-change-percentage-vs-previous-year\" class=\"anchor\" id=\"calculating-sales-change-percentage-vs-previous-year\" title=\"Anchor for Calculating Sales Change Percentage vs. Previous Year\">#<\/a><\/h3>\n\n\n\n<p>The following <code>SELECT<\/code> statement uses the <code>LAG<\/code> window function to calculate the percentage change in sales compared to the previous year:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    year,\n    amount,\n    LAG(amount) <span class=\"hljs-keyword\">OVER<\/span> (<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year) <span class=\"hljs-keyword\">AS<\/span> previous_year_amount,\n    ROUND((amount - LAG(amount) <span class=\"hljs-keyword\">OVER<\/span> (<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year)) \/ LAG(amount) <span class=\"hljs-keyword\">OVER<\/span> (<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year) * <span class=\"hljs-number\">100<\/span>, <span class=\"hljs-number\">2<\/span>) <span class=\"hljs-keyword\">AS<\/span> sales_change_percentage\n<span class=\"hljs-keyword\">FROM<\/span> \n    sales_by_years;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=lag&amp;q=U0VMRUNUIHllYXIsIGFtb3VudCwgTEFHKGFtb3VudCkgT1ZFUiAoT1JERVIgQlkgeWVhcikgQVMgcHJldmlvdXNfeWVhcl9hbW91bnQsIFJPVU5EKChhbW91bnQgLSBMQUcoYW1vdW50KSBPVkVSIChPUkRFUiBCWSB5ZWFyKSkgLyBMQUcoYW1vdW50KSBPVkVSIChPUkRFUiBCWSB5ZWFyKSAqIDEwMCwgMikgQVMgc2FsZXNfY2hhbmdlX3BlcmNlbnRhZ2UgRlJPTSBzYWxlc19ieV95ZWFyczs%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">year |  amount   | previous_year_amount | sales_change_percentage\n------+-----------+----------------------+-------------------------\n 2019 | 513700.00 |                 NULL |                    NULL\n 2020 | 490000.00 |            513700.00 |                   -4.61\n 2021 | 512000.00 |            490000.00 |                    4.49\n 2022 | 483200.00 |            512000.00 |                   -5.63\n 2023 | 491000.00 |            483200.00 |                    1.61<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>LAG(amount) OVER (ORDER BY year)<\/code>: Returns the sales amount from the previous year.<\/li>\n\n\n\n<li><code>(amount - LAG(amount) OVER (ORDER BY year)) \/ LAG(amount) OVER (ORDER BY year) * 100<\/code>: Calculates the percentage change in sales compared to the previous year.<\/li>\n\n\n\n<li><code>ROUND()<\/code>: Rounds the percentage change to two decimal places.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id='comparing-sales-by-products'>Comparing Sales by Products <a href=\"#comparing-sales-by-products\" class=\"anchor\" id=\"comparing-sales-by-products\" title=\"Anchor for Comparing Sales by Products\">#<\/a><\/h3>\n\n\n\n<p>The following <code>SELECT<\/code> statement uses the <code>LAG()<\/code> window function to compare the sales of different products year by year:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  year,\n  product,\n  amount,\n  LAG(amount) <span class=\"hljs-keyword\">OVER<\/span> (\n    <span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> product\n    <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year\n  ) <span class=\"hljs-keyword\">AS<\/span> previous_year_amount\n<span class=\"hljs-keyword\">FROM<\/span>\n  sales;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=lag&amp;q=U0VMRUNUIHllYXIsIHByb2R1Y3QsIGFtb3VudCwgTEFHKGFtb3VudCkgT1ZFUiAoIFBBUlRJVElPTiBCWSBwcm9kdWN0IE9SREVSIEJZIHllYXIgKSBBUyBwcmV2aW91c195ZWFyX2Ftb3VudCBGUk9NIHNhbGVzOw%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\"> year | product |  amount   | previous_year_amount\n------+---------+-----------+----------------------\n 2019 | Galaxy  | 296000.00 |                 NULL\n 2020 | Galaxy  | 273000.00 |            296000.00\n 2021 | Galaxy  | 272000.00 |            273000.00\n 2022 | Galaxy  | 258200.00 |            272000.00\n 2023 | Galaxy  | 260000.00 |            258200.00\n 2019 | iPhone  | 217700.00 |                 NULL\n 2020 | iPhone  | 217000.00 |            217700.00\n 2021 | iPhone  | 240000.00 |            217000.00\n 2022 | iPhone  | 225000.00 |            240000.00\n 2023 | iPhone  | 231000.00 |            225000.00<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>PARTITION BY product<\/code>: Divides the rows into partitions based on the product.<\/li>\n\n\n\n<li><code>ORDER BY year<\/code>: Orders the rows within each partition by year.<\/li>\n\n\n\n<li><code>LAG(amount)<\/code>: Applies to each partition (product) and returns the sales amount from the previous year for the same product.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id='comparing-sales-vs-previous-year-by-product-in-percentage'>Comparing Sales vs. Previous Year by Product in Percentage <a href=\"#comparing-sales-vs-previous-year-by-product-in-percentage\" class=\"anchor\" id=\"comparing-sales-vs-previous-year-by-product-in-percentage\" title=\"Anchor for Comparing Sales vs. Previous Year by Product in Percentage\">#<\/a><\/h3>\n\n\n\n<p>The following <code>SELECT<\/code> statement uses the <code>LAG()<\/code> function to calculate the percentage change in sales for each product compared to the previous year:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  year,\n  product,\n  amount,\n  LAG(amount) <span class=\"hljs-keyword\">OVER<\/span> (\n    <span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> product\n    <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year\n  ) <span class=\"hljs-keyword\">AS<\/span> previous_year_amount,\n  ROUND(\n    (\n      amount - LAG(amount) <span class=\"hljs-keyword\">OVER<\/span> (\n        <span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> product\n        <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year\n      )\n    ) \/ LAG(amount) <span class=\"hljs-keyword\">OVER<\/span> (\n      <span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> product\n      <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year\n    ) * <span class=\"hljs-number\">100<\/span>,\n    <span class=\"hljs-number\">2<\/span>\n  ) <span class=\"hljs-keyword\">AS<\/span> sales_change_percentage\n<span class=\"hljs-keyword\">FROM<\/span>\n  sales;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=lag&amp;q=U0VMRUNUIHllYXIsIHByb2R1Y3QsIGFtb3VudCwgTEFHKGFtb3VudCkgT1ZFUiAoIFBBUlRJVElPTiBCWSBwcm9kdWN0IE9SREVSIEJZIHllYXIgKSBBUyBwcmV2aW91c195ZWFyX2Ftb3VudCwgUk9VTkQoICggYW1vdW50IC0gTEFHKGFtb3VudCkgT1ZFUiAoIFBBUlRJVElPTiBCWSBwcm9kdWN0IE9SREVSIEJZIHllYXIgKSApIC8gTEFHKGFtb3VudCkgT1ZFUiAoIFBBUlRJVElPTiBCWSBwcm9kdWN0IE9SREVSIEJZIHllYXIgKSAqIDEwMCwgMiApIEFTIHNhbGVzX2NoYW5nZV9wZXJjZW50YWdlIEZST00gc2FsZXM7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\"> year | product |  amount   | previous_year_amount | sales_change_percentage\n------+---------+-----------+----------------------+-------------------------\n 2019 | Galaxy  | 296000.00 |                 NULL |                    NULL\n 2020 | Galaxy  | 273000.00 |            296000.00 |                   -7.77\n 2021 | Galaxy  | 272000.00 |            273000.00 |                   -0.37\n 2022 | Galaxy  | 258200.00 |            272000.00 |                   -5.07\n 2023 | Galaxy  | 260000.00 |            258200.00 |                    0.70\n 2019 | iPhone  | 217700.00 |                 NULL |                    NULL\n 2020 | iPhone  | 217000.00 |            217700.00 |                   -0.32\n 2021 | iPhone  | 240000.00 |            217000.00 |                   10.60\n 2022 | iPhone  | 225000.00 |            240000.00 |                   -6.25\n 2023 | iPhone  | 231000.00 |            225000.00 |                    2.67<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>PARTITION BY product<\/code>: Divides the result set into partitions based on the product.<\/li>\n\n\n\n<li><code>ORDER BY year<\/code>: Sorts the rows within each partition by year in ascending order.<\/li>\n\n\n\n<li><code>LAG(amount)<\/code>: Retrieves the sales amount from the previous year for the same product.<\/li>\n\n\n\n<li><code>(amount - LAG(amount) OVER (PARTITION BY product ORDER BY year)) \/ LAG(amount) OVER (PARTITION BY product ORDER BY year) * 100<\/code>: Calculates the percentage change in sales for the same product compared to the previous year.<\/li>\n\n\n\n<li><code>ROUND<\/code>: Rounds the percentage change to two decimal places.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the PostgreSQL <code>LAG()<\/code> window function to access data from a previous row in the same partition.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='quiz'>Quiz <a href=\"#quiz\" class=\"anchor\" id=\"quiz\" title=\"Anchor for Quiz\">#<\/a><\/h2>\n\n\n\n<iframe loading=\"lazy\"\n  name=\"quiz\"\n  src=\"\/quiz\/?quiz=lag\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\n\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1167\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL LAG Window Function\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1167\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL LAG Window Function\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to use the PostgreSQL LAG window function to compare the current row&#8217;s value with the previous row.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1072,"menu_order":9,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1167","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>PostgreSQL LAG Window Function<\/title>\n<meta name=\"description\" content=\"In this tutorial, you&#039;ll learn how to use the PostgreSQL LAG window function to compare the current row&#039;s value with the previous row.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PostgreSQL LAG Window Function\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you&#039;ll learn how to use the PostgreSQL LAG window function to compare the current row&#039;s value with the previous row.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/\" \/>\n<meta property=\"og:site_name\" content=\"PostgreSQL Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2025-01-05T14:16:10+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-lag\\\/\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-lag\\\/\",\"name\":\"PostgreSQL LAG Window Function\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\"},\"datePublished\":\"2024-12-21T15:30:12+00:00\",\"dateModified\":\"2025-01-05T14:16:10+00:00\",\"description\":\"In this tutorial, you'll learn how to use the PostgreSQL LAG window function to compare the current row's value with the previous row.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-lag\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-lag\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-lag\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.pgtutorial.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PostgreSQL Window Functions\",\"item\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"PostgreSQL LAG Window Function\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/\",\"name\":\"PostgreSQL Tutorial\",\"description\":\"Learn PostgreSQL from Scratch\",\"alternateName\":\"PostgreSQL\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.pgtutorial.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"PostgreSQL LAG Window Function","description":"In this tutorial, you'll learn how to use the PostgreSQL LAG window function to compare the current row's value with the previous row.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/","og_locale":"en_US","og_type":"article","og_title":"PostgreSQL LAG Window Function","og_description":"In this tutorial, you'll learn how to use the PostgreSQL LAG window function to compare the current row's value with the previous row.","og_url":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/","og_site_name":"PostgreSQL Tutorial","article_modified_time":"2025-01-05T14:16:10+00:00","twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/","url":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/","name":"PostgreSQL LAG Window Function","isPartOf":{"@id":"https:\/\/www.pgtutorial.com\/#website"},"datePublished":"2024-12-21T15:30:12+00:00","dateModified":"2025-01-05T14:16:10+00:00","description":"In this tutorial, you'll learn how to use the PostgreSQL LAG window function to compare the current row's value with the previous row.","breadcrumb":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-lag\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pgtutorial.com\/"},{"@type":"ListItem","position":2,"name":"PostgreSQL Window Functions","item":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/"},{"@type":"ListItem","position":3,"name":"PostgreSQL LAG Window Function"}]},{"@type":"WebSite","@id":"https:\/\/www.pgtutorial.com\/#website","url":"https:\/\/www.pgtutorial.com\/","name":"PostgreSQL Tutorial","description":"Learn PostgreSQL from Scratch","alternateName":"PostgreSQL","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pgtutorial.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/1167","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/comments?post=1167"}],"version-history":[{"count":9,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/1167\/revisions"}],"predecessor-version":[{"id":1474,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/1167\/revisions\/1474"}],"up":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/1072"}],"wp:attachment":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/media?parent=1167"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}