Selecting the Last Record of a Table in SQL
When querying a database, it may be necessary to retrieve only the most recent record from a table. This article discusses techniques for selecting the last record while addressing a common error encountered using the LIMIT clause.
Selecting the Last Record
To select the last record of a table, the ORDER BY clause can be used to sort the records in descending order based on an identifier field, such as the ID. Combined with the LIMIT clause, which restricts the number of returned records, this approach effectively retrieves the last record.
Example Code
The following code illustrates how to select the last record in a SQL Server database using the TOP clause:
SELECT TOP 1 * FROM Table ORDER BY ID DESC
For MySQL, the LIMIT clause can be used:
SELECT * FROM Table ORDER BY ID DESC LIMIT 1
In C#, the following code snippet demonstrates the selection of the last record:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HELPDESK_OUTLOOKConnectionString3"].ToString()); conn.Open(); SqlDataReader myReader = null; SqlCommand myCommand = new SqlCommand("SELECT TOP 1 * FROM HD_AANVRAGEN ORDER BY aanvraag_id DESC", conn); myReader = myCommand.ExecuteReader(); while (myReader.Read()) { // Process the last record here }
Resolving the LIMIT Syntax Error
The error "Line 1: Incorrect syntax near 'LIMIT'." indicates an incorrect usage of the LIMIT clause. In SQL, the LIMIT clause is used to specify the number of records to be returned. However, it is not supported in all databases. For example, in SQL Server, the TOP clause is used instead.
To resolve this error, replace the LIMIT clause with the appropriate clause for the database being used, such as TOP or OFFSET-FETCH.
The above is the detailed content of How to Select the Last Record from a SQL Table?. For more information, please follow other related articles on the PHP Chinese website!