mysql
  1. mysql-last

MySQL Aggregate Function: LAST()

The LAST() function in MySQL is an aggregate function that returns the value of the last row in a group. In this tutorial, we'll cover the syntax of the LAST() function, as well as provide an example and explanation of how it works.

Syntax

The syntax of the LAST() function is as follows:

LAST(expr)

The expr argument is an expression that refers to the column or expression for which you want to retrieve the last value. The LAST() function ignores NULL values, so if the last row of a group contains a NULL value, the function will return the value of the previous row in the group instead.

Example

Consider the following orders table:

order_id customer_id order_date
1 101 2022-04-01
2 102 2022-04-02
3 101 2022-04-02
4 103 2022-04-03
5 102 2022-04-03

To retrieve the last order date for each customer, we can use the following query:

SELECT customer_id, LAST(order_date) AS last_order_date
FROM orders
GROUP BY customer_id;

The output of this query would be:

customer_id last_order_date
101 2022-04-02
102 2022-04-03
103 2022-04-03

In this example, we retrieved the customer_id and the last order_date for each customer using the LAST() function. We then grouped the results by customer_id using the GROUP BY clause.

Explanation

The LAST() function returns the value of the last row in a group. In our example query, we grouped the orders table by customer_id using the GROUP BY clause. The LAST() function then retrieved the last value of the order_date column for each group.

If the last row of a group contains a NULL value, the LAST() function ignores it and returns the value of the previous row in the group. This behavior is useful when working with incomplete or missing data.

Use

The LAST() function can be used when you want to retrieve the value of the last row in a group. This is useful when you want to track the last value of a specific column or expression for each group.

Important Points

  • The LAST() function is an aggregate function that returns the value of the last row in a group.
  • The LAST() function ignores NULL values, so if the last row of a group contains a NULL value, the function will return the value of the previous row in the group instead.
  • The LAST() function can be used with the GROUP BY clause to group rows by a specific column or expression.

Summary

In this tutorial, we covered the syntax of the LAST() function in MySQL, as well as provided an example and explanation of how it works. The LAST() function is useful for retrieving the last value of a specific column or expression for each group.

Published on: