Open In App

PostgreSQL – LAST_VALUE Function

Last Updated : 19 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

PostgreSQL LAST_VALUE Function Example

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

PostgreSQL LAST_VALUE Function Example

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.

FAQs

What does last_value do?

The last_value function in SQL returns the last value in an ordered set of rows within a window or partition. It is commonly used in conjunction with window functions like OVER.

What is the range of last_value in SQL?

The range of last_value is defined by the rows within the current window or partition, determined by the OVER clause. The function only evaluates values within this specified range.

What is the function of first_value in Postgres?

The first_value function in PostgreSQL retrieves the first value in an ordered set of rows within a defined window. It is useful for accessing the initial record in a sorted dataset or partition



Similar Reads

three90RightbarBannerImg