SQL LAST() Function |
SQL Sample Code - SQL LAST() Function |
| SELECT LAST(column_name) FROM table_name; |
Note: The LAST() function is not supported by certain databases. See the LIMIT function for an alternative.
See the SQL samples section below for an explanation of the LAST function.
What does the LAST() Function do? |
The SQL LAST() function simply retrieves the LAST value that exists in a specified column.
The LAST function is particularly useful in SQL queries where the data-set values change on a regular basis.
Sample 1 – SQL LAST() Function |
In this SQL sample we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
In this SQL sample we simply want to know the last Sales figure in the tblCompany table.
Use the SELECT statement below:
| SELECT LAST(Sales) AS Sales_Last FROM tblCompany; |
The result will look like this:
| Sales_Last |
| 17000 |
Note: the AS operator is used to name the result column as ‘Sales_Last’. See the Alias section of this website to learn more about renaming database columns and tables.
Sample 2 – SQL LAST() Function using ORDER BY. |
In this example we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
In this SQL sample we want to know the last Sales record when the values in the tblCompany table are in ascending order ‘ASC’.
Use the SELECT statement below:
| SELECT LAST(Sales) FROM tblCompany ORDER BY Sales ASC; |
The result will look like this:
| LAST(Sales) |
| 20000 |
Note: To learn more about ordering records go to the ORDER BY section.
Related SQL Sample Code:
|
|