PostgreSQL - LAST_VALUE Function
Last Updated :
19 Nov, 2024
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 explain the PostgreSQL LAST_VALUE() function in detail, covering its syntax, key terms, practical examples, and important points. Whether we’re a beginner or an experienced SQL developer, this guide will help us fully understand and use this function for efficient data querying.
What is PostgreSQL LAST_VALUE Function?
The LAST_VALUE() function in PostgreSQL is used to retrieve the last value of a column or expression in a specific window or partition. It is particularly useful for analyzing data trends, identifying extremes, and aggregating results within grouped data.
Syntax
LAST_VALUE ( expression )
OVER (
[PARTITION BY partition_expression, ... ]
ORDER BY sort_expression [ASC | DESC], ...
)
Key Terms
- expression: The column or expression from which the last value is extracted.
- PARTITION BY: Divides the result set into partitions to apply the function within each partition.
- ORDER BY: Specifies the order in which the rows are processed within each partition.
- frame_clause: Defines the subset of rows in the current partition over which the function operates.
PostgreSQL LAST_VALUE Function Examples
Let us take a look at some of the examples of LAST_VALUE Function in PostgreSQL to better understand the concept. These examples will demonstrate how to effectively use the LAST_VALUE() function to analyze and retrieve data based on the last value within an ordered set or partition in PostgreSQL.
Example 1: Retrieving the Mammal with the Longest Lifespan
This example demonstrates retrieving the mammal with the highest lifespan across all records. For this we need to first create two tables named 'Mammals' and 'Animal_groups' for the illustration.
Step 1: Create Tables
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 for the Mammal with the Longest Lifespan
The following query uses the LAST_VALUE() function to return all Mammals together with the mammal that has the highest lifespan.
Query:
SELECT
mammal_id,
mammal_name,
lifespan,
LAST_VALUE(mammal_name)
OVER(
ORDER BY lifespan
RANGE BETWEEN
UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING
) longest_lifespan
FROM
Mammals;
Output

Explanation:
This query returns each mammal along with the name of the mammal with the longest lifespan, calculated across the entire dataset with the help of LAST_VALUE() function.
Example 2: Finding the Longest-Lived Mammal per Animal Group
The following query uses the LAST_VALUE() function to return all mammals together with the mammal with longest lifespan per animal group.
Query:
SELECT
mammal_id,
mammal_name,
animal_id,
lifespan,
LAST_VALUE(mammal_name)
OVER(
PARTITION BY animal_id
ORDER BY lifespan
RANGE BETWEEN
UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING
) longest_life
FROM
Mammals;
Output

Explanation:
This query returns each mammal, along with the longest lifespan mammal within their respective animal groups. The PARTITION BY clause ensures that the calculation is done separately for each group defined by 'animal_id'.
Important Points About PostgreSQL LAST_VALUE Function
- Without a PARTITION BY clause, LAST_VALUE() considers the entire result set.
- The ORDER BY clause within the OVER clause dictates the order in which rows are considered to determine the "last" value.
- NULL values in the result set can affect the output. Ensure that the expression used in LAST_VALUE() does not include unexpected NULLs unless intended.
- Without a 'frame_clause', the default frame is used, which might not include all rows.
Conclusion
The PostgreSQL LAST_VALUE() function is an essential tool for analyzing data, especially when the final value of a dataset or partition is significant. By using partitioning and ordering, developers can achieve a high degree of control over their queries. Using the examples and Knowledge provided in this article to master the usage of the LAST_VALUE function in PostgreSQL.
Similar Reads
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 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
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 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
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Introduction of DBMS (Database Management System) A Database Management System (DBMS) is a software solution designed to efficiently manage, organize, and retrieve data in a structured manner. It serves as a critical component in modern computing, enabling organizations to store, manipulate, and secure their data effectively. From small application
8 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Window Functions in SQL SQL window functions are essential for advanced data analysis and database management. They enable calculations across a specific set of rows, known as a "window," while retaining the individual rows in the dataset. Unlike traditional aggregate functions that summarize data for the entire group, win
7 min read