{"id":1180,"date":"2024-12-22T12:00:03","date_gmt":"2024-12-22T05:00:03","guid":{"rendered":"https:\/\/www.pgtutorial.com\/?page_id=1180"},"modified":"2025-01-05T21:18:17","modified_gmt":"2025-01-05T14:18:17","slug":"postgresql-nth_value","status":"publish","type":"page","link":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/","title":{"rendered":"PostgreSQL NTH_VALUE Window Function"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the PostgreSQL <code>NTH_VALUE()<\/code> window function to access the n<sup>th<\/sup> row in a window frame.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='getting-started-with-the-postgresql-nth_value-window-function'>Getting Started with the PostgreSQL NTH_VALUE Window Function <a href=\"#getting-started-with-the-postgresql-nth_value-window-function\" class=\"anchor\" id=\"getting-started-with-the-postgresql-nth_value-window-function\" title=\"Anchor for Getting Started with the PostgreSQL NTH_VALUE Window Function\">#<\/a><\/h2>\n\n\n\n<p>The <code>NTH_VALUE()<\/code> is a window function that allows you to access the n<sup>th<\/sup> row within a window frame.<\/p>\n\n\n\n<p>Here&#8217;s the syntax of the <code>NTH_VALUE()<\/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\">NTH_VALUE(<span class=\"hljs-keyword\">value<\/span>, n) <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    &#91;frame_clause]\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>: This is a column or expression to retrieve the value from the n<sup>th<\/sup> row.<\/li>\n\n\n\n<li><code>n<\/code>: Specifies the <a href=\"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-row_number\/\">row number<\/a> within the window frame from which the <code>NTH_VALUE<\/code> function retrieves the value.<\/li>\n\n\n\n<li><code>OVER<\/code>: Defines the window over which the <code>NTH_VALUE<\/code> function applies.<\/li>\n\n\n\n<li><code>PARTITION BY<\/code>: Divides the result set into partitions by the <code>partition_expression<\/code>. The <code>partition_expression<\/code> can be one or more columns to group rows into partitions. If you omit the <code>PARTITION BY<\/code>, the function treats the entire result set as a single partition.<\/li>\n\n\n\n<li><code>ORDER BY<\/code>: Sorts the rows within each partition.<\/li>\n\n\n\n<li><code>frame_clause<\/code>: Defines the window frame for the function.<\/li>\n<\/ul>\n\n\n\n<p>The <code>NTH_VALUE()<\/code> function returns the value from the nth row of a window frame. If the n<sup>th<\/sup> row does not exist, the <code>NTH_VALUE()<\/code> function returns <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-not-null\/\">NULL<\/a><\/code>.<\/p>\n\n\n\n<p>The <code>NTH_VALUE<\/code> function is helpful for comparing a specific row with other rows within the same window frame.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='postgresql-nth_value-window-function-examples'>PostgreSQL NTH_VALUE Window Function Examples <a href=\"#postgresql-nth_value-window-function-examples\" class=\"anchor\" id=\"postgresql-nth_value-window-function-examples\" title=\"Anchor for PostgreSQL NTH_VALUE Window Function Examples\">#<\/a><\/h2>\n\n\n\n<p>Let&#8217;s explore some examples of using the <code>NTH_VALUE<\/code> function with the <code>sales<\/code> table and <code>sales_by_years<\/code> <a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-view\/\">view<\/a>:<\/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-nth_value-window-function-to-compare-yearly-sales'>Using PostgreSQL NTH_VALUE Window Function to Compare Yearly Sales <a href=\"#using-postgresql-nth_value-window-function-to-compare-yearly-sales\" class=\"anchor\" id=\"using-postgresql-nth_value-window-function-to-compare-yearly-sales\" title=\"Anchor for Using PostgreSQL NTH_VALUE Window Function to Compare Yearly Sales\">#<\/a><\/h3>\n\n\n\n<p>The following <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-select\/\">SELECT<\/a><\/code> statement uses the <code>NTH_VALUE<\/code> function to compare the sales amount of each year with the sales amount of the first year:<\/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  NTH_VALUE(amount, <span class=\"hljs-number\">1<\/span>) <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> first_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=U0VMRUNUIHllYXIsIGFtb3VudCwgTlRIX1ZBTFVFKGFtb3VudCwgMSkgT1ZFUiAoT1JERVIgQlkgeWVhcikgQVMgZmlyc3RfeWVhcl9hbW91bnQgRlJPTSBzYWxlc19ieV95ZWFyczs%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=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"> year |  amount   | first_year_amount\n<span class=\"hljs-comment\">------+-----------+-------------------<\/span>\n <span class=\"hljs-number\">2019<\/span> | <span class=\"hljs-number\">513700.00<\/span> |         <span class=\"hljs-number\">513700.00<\/span>\n <span class=\"hljs-number\">2020<\/span> | <span class=\"hljs-number\">490000.00<\/span> |         <span class=\"hljs-number\">513700.00<\/span>\n <span class=\"hljs-number\">2021<\/span> | <span class=\"hljs-number\">512000.00<\/span> |         <span class=\"hljs-number\">513700.00<\/span>\n <span class=\"hljs-number\">2022<\/span> | <span class=\"hljs-number\">483200.00<\/span> |         <span class=\"hljs-number\">513700.00<\/span>\n <span class=\"hljs-number\">2023<\/span> | <span class=\"hljs-number\">491000.00<\/span> |         <span class=\"hljs-number\">513700.00<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><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>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>ORDER BY<\/code> clause sorts the rows in the <code>sales_by_years<\/code> view by the year in ascending order.<\/li>\n\n\n\n<li>The <code>NTH_VALUE(amount, 1)<\/code> retrieves the amount value of the first row.<\/li>\n<\/ul>\n\n\n\n<p>The query returns the sales amount for each year alongside the sales amount from the first year, making it easy to compare.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='calculating-sales-change-percentage-vs-first-year'>Calculating Sales Change Percentage vs. First Year <a href=\"#calculating-sales-change-percentage-vs-first-year\" class=\"anchor\" id=\"calculating-sales-change-percentage-vs-first-year\" title=\"Anchor for Calculating Sales Change Percentage vs. First Year\">#<\/a><\/h3>\n\n\n\n<p>The following <code>SELECT<\/code> statement uses the <code>NTH_VALUE<\/code> function to calculate the percentage change in sales compared to the first 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  NTH_VALUE(amount, <span class=\"hljs-number\">1<\/span>) <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> first_year_amount,\n  ROUND(\n    (\n      amount - NTH_VALUE(amount, <span class=\"hljs-number\">1<\/span>) <span class=\"hljs-keyword\">OVER<\/span> (<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year)\n    ) \/ NTH_VALUE(amount, <span class=\"hljs-number\">1<\/span>) <span class=\"hljs-keyword\">OVER<\/span> (<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_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=U0VMRUNUIHllYXIsIGFtb3VudCwgTlRIX1ZBTFVFKGFtb3VudCwgMSkgT1ZFUiAoT1JERVIgQlkgeWVhcikgQVMgZmlyc3RfeWVhcl9hbW91bnQsIFJPVU5EKCAoIGFtb3VudCAtIE5USF9WQUxVRShhbW91bnQsIDEpIE9WRVIgKE9SREVSIEJZIHllYXIpICkgLyBOVEhfVkFMVUUoYW1vdW50LCAxKSBPVkVSIChPUkRFUiBCWSB5ZWFyKSAqIDEwMCwgMiApIEFTIHNhbGVzX2NoYW5nZV9wZXJjZW50YWdlIEZST00gc2FsZXNfYnlfeWVhcnM7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\"> year |  amount   | first_year_amount | sales_change_percentage\n------+-----------+-------------------+-------------------------\n 2019 | 513700.00 |         513700.00 |                    0.00\n 2020 | 490000.00 |         513700.00 |                   -4.61\n 2021 | 512000.00 |         513700.00 |                   -0.33\n 2022 | 483200.00 |         513700.00 |                   -5.94\n 2023 | 491000.00 |         513700.00 |                   -4.42<\/code><\/span><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>NTH_VALUE<\/code> function returns the amount of the first row (year).<\/li>\n\n\n\n<li>The expression <code>(amount - NTH_VALUE(amount, 1) OVER (ORDER BY year)) \/ NTH_VALUE(amount, 1) OVER (ORDER BY year) * 100<\/code> calculates the percentage change in sales compared to the first year.<\/li>\n\n\n\n<li>The <code>ROUND()<\/code> function 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>NTH_VALUE()<\/code> window function to compare the sales of different products year by year with the first year&#8217;s sales for each product:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" 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    NTH_VALUE(amount, <span class=\"hljs-number\">1<\/span>) <span class=\"hljs-keyword\">OVER<\/span> (<span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> product <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year) <span class=\"hljs-keyword\">AS<\/span> first_year_amount\n<span class=\"hljs-keyword\">FROM<\/span> sales;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><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=U0VMRUNUIHllYXIsIHByb2R1Y3QsIGFtb3VudCwgTlRIX1ZBTFVFKGFtb3VudCwgMSkgT1ZFUiAoUEFSVElUSU9OIEJZIHByb2R1Y3QgT1JERVIgQlkgeWVhcikgQVMgZmlyc3RfeWVhcl9hbW91bnQgRlJPTSBzYWxlczs%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\"><span><code class=\"hljs\"> year | product |  amount   | first_year_amount\n------+---------+-----------+-------------------\n 2019 | Galaxy  | 296000.00 |         296000.00\n 2020 | Galaxy  | 273000.00 |         296000.00\n 2021 | Galaxy  | 272000.00 |         296000.00\n 2022 | Galaxy  | 258200.00 |         296000.00\n 2023 | Galaxy  | 260000.00 |         296000.00\n 2019 | iPhone  | 217700.00 |         217700.00\n 2020 | iPhone  | 217000.00 |         217700.00\n 2021 | iPhone  | 240000.00 |         217700.00\n 2022 | iPhone  | 225000.00 |         217700.00\n 2023 | iPhone  | 231000.00 |         217700.00<\/code><\/span><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>PARTITION BY<\/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.<\/li>\n\n\n\n<li><code>NTH_VALUE(amount, 1) OVER (PARTITION BY product ORDER BY year)<\/code>: Returns the amount from the first year for the same partition (or product).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id='comparing-sales-vs-first-year-by-product-in-percentage'>Comparing Sales vs. First Year by Product in Percentage <a href=\"#comparing-sales-vs-first-year-by-product-in-percentage\" class=\"anchor\" id=\"comparing-sales-vs-first-year-by-product-in-percentage\" title=\"Anchor for Comparing Sales vs. First Year by Product in Percentage\">#<\/a><\/h3>\n\n\n\n<p>The following <code>SELECT<\/code> statement uses the <code>NTH_VALUE()<\/code> window function to calculate the percentage change in sales for each product compared to the first 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    NTH_VALUE(amount, <span class=\"hljs-number\">1<\/span>) <span class=\"hljs-keyword\">OVER<\/span> (<span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> product <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year) <span class=\"hljs-keyword\">AS<\/span> first_year_amount,\n    ROUND((amount - NTH_VALUE(amount, <span class=\"hljs-number\">1<\/span>) <span class=\"hljs-keyword\">OVER<\/span> (<span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> product <span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> year)) \/ NTH_VALUE(amount, <span class=\"hljs-number\">1<\/span>) <span class=\"hljs-keyword\">OVER<\/span> (<span class=\"hljs-keyword\">PARTITION<\/span> <span class=\"hljs-keyword\">BY<\/span> product <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;<\/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=U0VMRUNUIHllYXIsIHByb2R1Y3QsIGFtb3VudCwgTlRIX1ZBTFVFKGFtb3VudCwgMSkgT1ZFUiAoUEFSVElUSU9OIEJZIHByb2R1Y3QgT1JERVIgQlkgeWVhcikgQVMgZmlyc3RfeWVhcl9hbW91bnQsIFJPVU5EKChhbW91bnQgLSBOVEhfVkFMVUUoYW1vdW50LCAxKSBPVkVSIChQQVJUSVRJT04gQlkgcHJvZHVjdCBPUkRFUiBCWSB5ZWFyKSkgLyBOVEhfVkFMVUUoYW1vdW50LCAxKSBPVkVSIChQQVJUSVRJT04gQlkgcHJvZHVjdCBPUkRFUiBCWSB5ZWFyKSAqIDEwMCwgMikgQVMgc2FsZXNfY2hhbmdlX3BlcmNlbnRhZ2UgRlJPTSBzYWxlczs%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\"><span><code class=\"hljs\"> year | product |  amount   | first_year_amount | sales_change_percentage\n------+---------+-----------+-------------------+-------------------------\n 2019 | Galaxy  | 296000.00 |         296000.00 |                    0.00\n 2020 | Galaxy  | 273000.00 |         296000.00 |                   -7.77\n 2021 | Galaxy  | 272000.00 |         296000.00 |                   -8.11\n 2022 | Galaxy  | 258200.00 |         296000.00 |                  -12.77\n 2023 | Galaxy  | 260000.00 |         296000.00 |                  -12.16\n 2019 | iPhone  | 217700.00 |         217700.00 |                    0.00\n 2020 | iPhone  | 217000.00 |         217700.00 |                   -0.32\n 2021 | iPhone  | 240000.00 |         217700.00 |                   10.24\n 2022 | iPhone  | 225000.00 |         217700.00 |                    3.35\n 2023 | iPhone  | 231000.00 |         217700.00 |                    6.11<\/code><\/span><\/pre>\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>PARTITION BY<\/code>: Divides the result set into partitions based on the product.<\/li>\n\n\n\n<li><code>ORDER BY<\/code>: Sorts the rows within each partition by year in ascending order.<\/li>\n\n\n\n<li><code>NTH_VALUE<\/code>: Returns the amount from the first year for the same product.<\/li>\n\n\n\n<li>The expression <code>(amount - NTH_VALUE(amount, 1) OVER (PARTITION BY product ORDER BY year)) \/ NTH_VALUE(amount, 1) OVER (PARTITION BY product ORDER BY year) * 100<\/code> computes the percentage change in sales compared to the first year for the same product.<\/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 <code>NTH_VALUE<\/code> window function to access a specific value within 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=nth_value\"\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=\"1180\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL NTH_VALUE 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=\"1180\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL NTH_VALUE 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 NTH_VALUE() function to access the nth row in a window frame.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1072,"menu_order":10,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1180","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 NTH_VALUE Window Function<\/title>\n<meta name=\"description\" content=\"In this tutorial, you&#039;ll learn how to use the PostgreSQL NTH_VALUE() function to access the nth row in a window frame.\" \/>\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-nth_value\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PostgreSQL NTH_VALUE Window Function\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you&#039;ll learn how to use the PostgreSQL NTH_VALUE() function to access the nth row in a window frame.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/\" \/>\n<meta property=\"og:site_name\" content=\"PostgreSQL Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2025-01-05T14:18:17+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-nth_value\\\/\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-nth_value\\\/\",\"name\":\"PostgreSQL NTH_VALUE Window Function\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\"},\"datePublished\":\"2024-12-22T05:00:03+00:00\",\"dateModified\":\"2025-01-05T14:18:17+00:00\",\"description\":\"In this tutorial, you'll learn how to use the PostgreSQL NTH_VALUE() function to access the nth row in a window frame.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-nth_value\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-nth_value\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-window-functions\\\/postgresql-nth_value\\\/#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 NTH_VALUE 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 NTH_VALUE Window Function","description":"In this tutorial, you'll learn how to use the PostgreSQL NTH_VALUE() function to access the nth row in a window frame.","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-nth_value\/","og_locale":"en_US","og_type":"article","og_title":"PostgreSQL NTH_VALUE Window Function","og_description":"In this tutorial, you'll learn how to use the PostgreSQL NTH_VALUE() function to access the nth row in a window frame.","og_url":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/","og_site_name":"PostgreSQL Tutorial","article_modified_time":"2025-01-05T14:18:17+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-nth_value\/","url":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/","name":"PostgreSQL NTH_VALUE Window Function","isPartOf":{"@id":"https:\/\/www.pgtutorial.com\/#website"},"datePublished":"2024-12-22T05:00:03+00:00","dateModified":"2025-01-05T14:18:17+00:00","description":"In this tutorial, you'll learn how to use the PostgreSQL NTH_VALUE() function to access the nth row in a window frame.","breadcrumb":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.pgtutorial.com\/postgresql-window-functions\/postgresql-nth_value\/#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 NTH_VALUE 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\/1180","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=1180"}],"version-history":[{"count":7,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/1180\/revisions"}],"predecessor-version":[{"id":1475,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/1180\/revisions\/1475"}],"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=1180"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}