Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SQL LAST() Function

SQL LAST() Function


The LAST() Function

The LAST() function returns the value of the last record in the specified column.

SQL LAST() Syntax

SELECT LAST(column_name) FROM table_name;

**Note:** Only MS Access supports the LAST() function.


SQL LAST() Workaround in SQL Server, MySQL, and Oracle

SQL Server Syntax

SELECT TOP 1

column_name

FROM

table_name

ORDER BY

column_name

DESC;

Example

SELECT TOP 1 name FROM Websites

ORDER BY id DESC;

MySQL Syntax

SELECT

column_name

FROM

table_name

ORDER BY

column_name

DESC

LIMIT 1;

Example

SELECT name FROM Websites

ORDER BY id DESC

LIMIT 1;

Oracle Syntax

SELECT

column_name

FROM

table_name

ORDER BY

column_name

DESC

WHERE ROWNUM <=1;

Example

SELECT name FROM Websites

ORDER BY id DESC

WHERE ROWNUM <=1;


Demonstration Database

In this tutorial, we will use the RUNOOB sample database.

Below is the data selected from the "Websites" table:



+----+--------------+---------------------------+-------+---------+

| id | name         | url                       | alexa | country |

+----+--------------+---------------------------+-------+---------+

| 1  | Google       | https://www.google.cm/    | 1     | USA     |

| 2  | 淘宝          | https://www.taobao.com/   | 13    | CN      |

| 3  | Runoob Tutorial      | http://www.runoob.com/    | 4689  | CN      |

| 4  | 微博          | http://weibo.com/         | 20    | CN      |

| 5  | Facebook     | https://www.facebook.com/ | 3     | USA     |

|  6 | 百度         | https://www.baidu.com/    |     4 | CN      |

|  7 | stackoverflow | http://stackoverflow.com/ |     0 | IND     |

+----+---------------+---------------------------+-------+---------+


SQL LAST() Examples

The following SQL statement selects the value of the last record in the "name" column of the "Websites" table:

Example

SELECT name FROM Websites

ORDER BY id DESC

LIMIT 1;

The result of executing the above SQL is as follows: