📜  MySQL last()(1)

📅  最后修改于: 2023-12-03 15:17:45.923000             🧑  作者: Mango

MySQL LAST()

Introduction

In MySQL, the LAST() function is used to return the last value in a sorted column from a result set. It is commonly used to retrieve the last record or value stored in a specific column of a table. With the help of LAST(), you can easily find the most recent or latest entry in a table based on a specified column.

Syntax

The syntax for using the LAST() function in MySQL is as follows:

LAST(value)

Here, value represents the column name or expression from which you want to extract the last value. The LAST() function does not accept multiple parameters.

Usage

Consider the following example table called orders:

| order_id | customer | order_date | |----------|----------|------------| | 1 | John | 2022-01-05 | | 2 | Lisa | 2022-01-10 | | 3 | Mark | 2022-01-08 | | 4 | Emma | 2022-01-12 | | 5 | David | 2022-01-03 |

To retrieve the last order_date from the orders table, you can use the following query:

SELECT LAST(order_date) AS last_order_date FROM orders;

This will produce the following result:

| last_order_date | |-----------------| | 2022-01-12 |

In the above example, the LAST() function returns the latest order_date by sorting the column in descending order.

Notes
  • The LAST() function is typically used in conjunction with the SELECT statement to retrieve the last value from a column.
  • If the specified column contains NULL values, the LAST() function will still return the last non-NULL value from the sorted column.
  • If you want to retrieve the last value from a specific column in a table without sorting, you can use the MAX() function instead.
  • The LAST() function can also be used with other functions like GROUP BY or ORDER BY to retrieve the last value for specific groups or based on certain conditions.
Conclusion

The LAST() function in MySQL allows you to easily extract the last value from a sorted column. It is useful for finding the most recent or latest entry in a table. By using the LAST() function, you can efficiently retrieve the desired information from your database.