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 - User Defined Functions
Next article icon

PostgreSQL – FIRST_VALUE Function

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

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 explain the syntax, usage, and practical examples of using the FIRST_VALUE() function in PostgreSQL, focusing on how it can improve data analysis by retrieving initial values within sorted or partitioned datasets.

Why Use the FIRST_VALUE() Function in PostgreSQL?

The FIRST_VALUE function in PostgreSQL is particularly valuable when working with grouped or partitioned data, such as identifying the lowest value within a subset of data. It’s widely used in analytics for tasks like tracking minimum or initial values across datasets

Syntax

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

Key Terms

  • expression: Evaluates the value to retrieve from the first row in the sorted partition. This can be a column, expression, or subquery returning a single value.
  • PARTITION BY clause: Divides rows into separate partitions within which the FIRST_VALUE() function operates independently. Useful for performing calculations or comparisons within specific groups of data.
  • ORDER BY clause: Specifies the sorting criteria for rows within each partition. Determines the order in which rows are processed by the FIRST_VALUE() function.
  • rows_range_clause: Optional clause that limits the range of rows within each partition that the function operates on. It defines a window frame within the partition for more precise control over result set boundaries.

Examples of PostgreSQL FIRST_VALUE Function

Let us take a look at some of the examples of the FIRST_VALUE Function in PostgreSQL to better understand its functionality and flexibility in data analysis. Here, we will explain its usage in both basic and partitioned query structures to highlight different applications.

Example 1: Basic Usage of FIRST_VALUE

Suppose we have two tables, Animal_groups and Mammals, and we want to use the FIRST_VALUE() function to retrieve the mammal with the lowest lifespan.

Step 1: Create Sample Tables and Data

CREATE TABLE Animal_groups (
animal_id serial PRIMARY KEY,
animal_name VARCHAR (255) NOT NULL
);

CREATE TABLE Mammals (
mammal_id serial PRIMARY KEY,
mammal_name VARCHAR (255) NOT NULL,
lifespan DECIMAL (11, 2),
animal_id INT NOT NULL,
FOREIGN KEY (animal_id) REFERENCES Animal_groups (animal_id)
);

Step 2: Insert Data

INSERT INTO Animal_groups (animal_name)
VALUES
('Terrestrial'),
('Aquatic'),
('Winged');

INSERT INTO Mammals(mammal_name, animal_id, lifespan)
VALUES
('Cow', 1, 10),
('Dog', 1, 7),
('Ox', 1, 13),
('Wolf', 1, 11),
('Blue Whale', 2, 80),
('Dolphin', 2, 5),
('Sea Horse', 2, 3),
('Octopus', 2, 8),
('Bat', 3, 4),
('Flying Squirrels', 3, 1),
('Petaurus', 3, 2);

Step 3: Query Using FIRST_VALUE()

To find the mammal with the lowest lifespan across all animal groups, use the FIRST_VALUE() function with an ORDER BY clause with the help of the below given query.

Query:

SELECT 
mammal_id,
mammal_name,
mammal_id,
lifespan,
FIRST_VALUE(mammal_name)
OVER(
ORDER BY lifespan
) lowest_lifespan
FROM
Mammals;

Output

PostgreSQL FIRST_VALUE Function Example

Explanation:

This query returns all mammals along with the mammal having the lowest lifespan across the entire dataset. Here, ‘FIRST_VALUE(mammal_name) OVER(ORDER BY lifespan)' identifies the mammal with the smallest lifespan.

Example 2: Partitioned by Animal Groups

The below statement uses the FIRST_VALUE() function to return all mammals grouped by the animal group. And for each animal group, it returns the mammal with the lowest lifespan.

Query:

SELECT 
mammal_id,
mammal_name,
mammal_id,
lifespan,
FIRST_VALUE(mammal_name)
OVER(
PARTITION BY animal_id
ORDER BY lifespan
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) lowest_lifespan
FROM
Mammals;

Output

PostgreSQL FIRST_VALUE Function Example

Explanation:

This query returns all mammals along with the mammal having the lowest lifespan across the entire dataset. Here, ‘FIRST_VALUE(mammal_name) OVER(ORDER BY lifespan)' identifies the mammal with the smallest lifespan.

Important Points About PostgreSQL FIRST_VALUE Function

  • If multiple rows have the same value for the ORDER BY expression, the FIRST_VALUE() function returns the first row it encounters based on the order of the rows in the table.
  • The ‘rows_range_clause' (e.g., ROWS BETWEEN or RANGE BETWEEN) can limit the number of rows considered within each partition. However, for FIRST_VALUE(), specifying the frame is generally not necessary unless combined with other window functions that require precise row control.
  • The ordering of rows within partitions directly affects the result of FIRST_VALUE(). Ensure the ORDER BY clause accurately reflects the desired sorting to get meaningful results.
  • NULL values affect FIRST_VALUE() results, as they are sorted last in ascending order and first in descending order. Use NULLS FIRST or NULLS LAST in the ORDER BY clause for precise control.

Conclusion

The FIRST_VALUE function in PostgreSQL enables effective data analysis, especially for tracking initial values within ordered or grouped data. This function, when combined with clauses like PARTITION BY and ORDER BY, provides excellent flexibility in SQL queries.

The FIRST_VALUE function is particularly useful for summarizing datasets, allowing us to quickly access specific insights like the lowest or earliest value across different groups or partitions, enhancing the power of analytical SQL operations in PostgreSQL.



Next Article
PostgreSQL - User Defined Functions

R

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

Similar Reads

  • PostgreSQL - NTH_VALUE Function
    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 h
    5 min read
  • 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 - FORMAT Function
    The PostgreSQL format() function is a powerful tool for string formatting by allowing developers to insert variables into strings using format specifiers like %s, %I, and %L. This function is especially useful for building dynamic SQL queries and ensuring proper formatting of identifiers. It simplif
    3 min read
  • PostgreSQL - UPPER Function
    In PostgreSQL, the UPPER function is utilized to convert a string into uppercase. This function is handy when you need to standardize text data by converting it to a uniform case, especially for comparison or display purposes. Let us get a better understanding of the UPPER Function in PostgreSQL fro
    2 min read
  • PostgreSQL - User Defined Functions
    PostgreSQL, one of the most powerful open-source relational database management systems (RDBMS), provides a strong feature set for creating and utilizing user-defined functions (UDFs). By using user-defined functions, we can enhance the modularity, maintainability, and performance of our database ap
    5 min read
  • PostgreSQL - CHR Function
    The CHR() function in PostgreSQL is used to convert an integer ASCII code or a Unicode code point into its corresponding character. Let us better understand the concept of CHR Function in PostgreSQL from this article. SyntaxCHR(value);Parameter:value: The 'value' argument is generally an integer ASC
    2 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 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 - CURRENT_TIME Function
    The PostgreSQL CURRENT_TIME function returns the current time and the current time zone. This function is handy when you need to work with time-sensitive data in your database applications. Let us better understand the CURRENT_TIME Function in PostgreSQL from this article. SyntaxCURRENT_TIME(precisi
    3 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
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