PostgreSQL - FIRST_VALUE Function
Last Updated :
18 Nov, 2024
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

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

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.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Window Functions in SQL SQL window functions are essential for advanced data analysis and database management. It is a type of function that allows us to perform calculations across a specific set of rows related to the current row. These calculations happen within a defined window of data and they are particularly useful
6 min read
Top 60 DBMS Interview Questions with Answers for 2025 A Database Management System (DBMS) is the backbone of modern data storage and management. Understanding DBMS concepts is critical for anyone looking to work with databases. Whether you're preparing for your first job in database management or advancing in your career, being well-prepared for a DBMS
15+ min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced SQL (Structured Query Language) is a powerful and flexible tool for managing and manipulating relational databases. Regardless of our experience level, practising SQL exercises is essential for improving our skills. Regular practice not only enhances our understanding of SQL concepts but also builds
15+ min read
SQL Cheat Sheet ( Basic to Advanced) Creating and managing databases in SQL involves various commands and concepts that handle the structuring, querying, and manipulation of data. In this guide, we will see a comprehensive cheat sheet for essential SQL operations, offering a practical reference for tasks ranging from database creation
15 min read
SQL Views Views in SQL are a type of virtual table that simplifies how users interact with data across one or more tables. Unlike traditional tables, a view in SQL does not store data on disk; instead, it dynamically retrieves data based on a pre-defined query each time itâs accessed. SQL views are particular
7 min read
MySQL Tutorial This MySQL Tutorial is made for both beginners and experienced professionals. Whether you're starting with MYSQL basics or diving into advanced concepts, this free tutorial is the ideal guide to help you learn and understand MYSQL, no matter your skill level. From setting up your database to perform
11 min read
Indexing in Databases - Set 1 Indexing is a crucial technique used in databases to optimize data retrieval operations. It improves query performance by minimizing disk I/O operations, thus reducing the time it takes to locate and access data. Essentially, indexing allows the database management system (DBMS) to locate data more
8 min read