sql
  1. sql-select-last

SQL SELECT Statement - SELECT LAST

The SELECT LAST statement is used to retrieve the last row or record from a table in a database. It is helpful when you only need to access the latest or most recent information added to a table.

Syntax

The syntax for the SQL SELECT LAST statement is as follows:

SELECT column_name(s)
FROM table_name
ORDER BY column_name DESC
LIMIT 1;

Example

Consider a table named "employees" with the following data:

employee_id first_name last_name hire_date
1 John Smith 2022-01-01
2 Jane Doe 2022-01-03
3 Bob Johnson 2022-01-05

To retrieve the last record from the table, you would use the following SQL statement:

SELECT * 
FROM employees
ORDER BY hire_date DESC
LIMIT 1;

Output

The output of the SQL statement would be:

employee_id first_name last_name hire_date
3 Bob Johnson 2022-01-05

This is because the "Bob Johnson" record has the most recent hire date in the table.

Explanation

The SQL SELECT LAST statement is pretty straightforward. It retrieves the last row or record from a table in a database. To accomplish this, we use the ORDER BY clause to sort the table by the desired column in descending order (latest first), and then use the LIMIT 1 clause to limit the output to the first row only.

Use

The SQL SELECT LAST statement is typically used in cases where you only need the most recent record from a table. For example, you might want to retrieve the last order placed by a customer to determine the most recent purchase they made.

Important Points

  • The SELECT LAST statement can only retrieve the last record based on a single column.
  • The ORDER BY clause must be sorted in descending order (DESC) to return the most recent record.
  • The LIMIT 1 clause limits the result set to a single record.

Summary

The SQL SELECT LAST statement is a useful tool for retrieving the most recent record from a table in a database. By using the ORDER BY and LIMIT clauses, you can sort the table in descending order and limit the output to only the last record. This statement is particularly useful in cases where you only need the most recent information from a table.

Published on: