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 - NOW() Function
Next article icon

PostgreSQL – NTH_VALUE Function

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

The PostgreSQL NTH_VALUE() function is an essential tool in advanced SQL queries for analytical purposes. It allows us to retrieve the value from the nth row in an ordered set within a specified window. This functionality is invaluable when we need to pinpoint specific data points, such as the nth highest value or nth row in a group, making it a powerful function in the PostgreSQL window functions.

In this article, we will cover the syntax, usage, and practical examples of the PostgreSQL NTH_VALUE() function, highlighting how it can be applied for various data analysis tasks.

What is the PostgreSQL NTH_VALUE Function?

The NTH_VALUE() function is used in PostgreSQL to return the value of an expression from the nth row within a specified window of rows. This is particularly useful when we need to retrieve a specific row value in relation to other rows in the partitioned or ordered dataset.

Syntax

NTH_VALUE(expression, offset) 
OVER (
[ PARTITION BY partition_expression]
[ ORDER BY sort_expression [ASC | DESC]
frame_clause ]
)

Key Terms

  • expression: The column or expression from which the value is to be retrieved.
  • offset: A positive integer that indicates the row number, starting from the first row in the window.
  • PARTITION BY clause: Distributes rows into partitions to which the NTH_VALUE() function is applied.
  • ORDER BY clause: Sorts the result set to determine the nth row.
  • frame_clause: Defines the subset (or frame) of the partition used by the function.

Examples of PostgreSQL NTH_VALUE Function

Let us take a look at some of the examples of the NTH_VALUE Function in PostgreSQL to better understand the concept. where we will create two tables named ‘items’ and ‘groceries’:, insert values, and then query the data using the NTH_VALUE() function.

Step 1: Create Tables

We will create two tables, items and groceries, to store data about product groups and grocery items.

CREATE TABLE items(
group_id serial PRIMARY KEY,
group_name VARCHAR (100) NOT NULL
);

CREATE TABLE groceries(
gro_id serial PRIMARY KEY,
gro_name VARCHAR (100) NOT NULL,
price DECIMAL (11, 2),
group_id INT NOT NULL,
FOREIGN KEY (group_id) REFERENCES grocery (group_id)
);

Step 2: Insert Values into Tables

Now, let’s insert some sample data into both tables: items (for product groups) and groceries (for grocery items with their prices).

INSERT INTO groceries (group_name)
VALUES
('Cereal'),
('Fruit'),
('Vegetable');

INSERT INTO groceries (group_name, group_id, price)
VALUES
('Wheat', 1, 30),
('Rice', 1, 40),
('Barley', 1, 50),
('Corn', 1, 90),
('Apple', 2, 120),
('Banana', 2, 70),
('Pear', 2, 70),
('Mango', 2, 80),
('Brinjal', 3, 70),
('Capsicum', 3, 150),
('Potato', 3, 20);

Example 1: Using NTH_VALUE() to Find the Most Expensive Products

Suppose we have a products table and we want to retrieve the most expensive product. The below statement uses the NTH_VALUE() function to get the most expensive product in the list.

Query:

SELECT 
product_id,
product_name,
price,
NTH_VALUE(product_name, 2)
OVER(
ORDER BY price DESC
RANGE BETWEEN
UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING
)
FROM
products;

Output

PostgreSQL NTH_VALUE Function Example

Explanation:

  • This query retrieves all products and also shows the most expensive product based on the price column.
  • The NTH_VALUE(product_name, 2) function finds the product at the second position when ordered by price DESC.
  • The window frame RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ensures that all rows are considered for the nth value.

Example 2: Finding the Second Most Expensive Product per Group

The below PostgreSQL query uses the NTH_VALUE() function to return all products with the second most expensive product for each product group, making the process easy.

Query:

SELECT 
product_id,
product_name,
price,
group_id,
NTH_VALUE(product_name, 2)
OVER(
PARTITION BY group_id
ORDER BY price DESC
RANGE BETWEEN
UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING
)
FROM
products;

Output

PostgreSQL NTH_VALUE Function Example

Explanation:

  • The query uses the PARTITION BY group_id clause to group the products by their respective categories.
  • It then orders each group by price DESC to determine the second most expensive product in each group.
  • The NTH_VALUE() function retrieves the second highest product in each group

Important Points About PostgreSQL NTH_VALUE() Function

  • The NTH_VALUE() function retrieves the value of an expression from the nth row within a specified window of rows, providing powerful analytical capabilities for complex queries.
  • If the nth row does not exist within the window frame, the function returns NULL.
  • By using the PARTITION BY clause, we can perform the nth value calculation within each partition separately.
  • The window frame clause is optional but can be used to define a subset of the partition. Common clauses include: ‘ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING’ and ‘ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING’.

Conclusion

The PostgreSQL NTH_VALUE() function is an essential analytical tool for querying data in complex datasets. By using this function, we can easily extract specific values like the nth row from an ordered result set. Whether we are dealing with pricing data, product rankings, or time-series analysis, NTH_VALUE() offers great flexibility and precision. With its ability to partition data and order rows within each partition, the NTH_VALUE() function is incredibly powerful for both business intelligence and data analysis tasks



Next Article
PostgreSQL - NOW() Function

R

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

Similar Reads

  • PostgreSQL - LAST_VALUE Function
    The PostgreSQL LAST_VALUE() function is a powerful window function used to retrieve the last value within a specified window frame of a query result set. It is particularly beneficial for performing advanced data analysis and retrieving the final value in ordered partitions. In this article, we’ll e
    4 min read
  • PostgreSQL - FIRST_VALUE Function
    The FIRST_VALUE() function in PostgreSQL is a window function that retrieves the first value within an ordered set of rows, often within a specific partition. This feature is highly useful for data analysis and reporting by allowing targeted access to specific data points. In this article, we will e
    5 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 - SUM() Function
    The SUM() function in PostgreSQL is used to calculate the sum of values in a numeric column. This article will guide you through the syntax, important considerations, and practical examples of using the SUM() function in PostgreSQL. SyntaxSUM(column) The following points need to be kept in mind whil
    2 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 - RANK Function
    The RANK() function in PostgreSQL is an advanced analytical tool used to assign a rank to each row within a specific partition in a result set. This function is especially beneficial for ranking items based on specified criteria, making it ideal for data analysis and reporting tasks like identifying
    5 min read
  • PostgreSQL REVERSE() Function
    The REVERSE() function in PostgreSQL is a simple yet powerful tool used to reverse the order of characters in a given string. It takes one input which is a string and returns the characters in reverse order. This function is helpful when you need to transform data, run tests or validate information.
    4 min read
  • PostgreSQL - LAG Function
    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
    5 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 - 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
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