Home >Database >Mysql Tutorial >How Do I Select the Last Record from an SQL Table?
Selecting the Last Record in a Table
In SQL, retrieving all records from a table is straightforward using the SELECT * command. However, selecting the last record can be challenging. One common approach is to use the ORDER BY clause to sort the table in descending order and then limit the results to one using LIMIT 1.
Example:
Consider the task of selecting the last record from the HD_AANVRAGEN table in a database. The following SQL query can accomplish this:
SELECT TOP 1 * FROM HD_AANVRAGEN ORDER BY aanvraag_id DESC
This query will return the row with the highest value for the aanvraag_id column.
Troubleshooting Errors:
In the provided code snippet, the following error is encountered:
Line 1: Incorrect syntax near 'LIMIT'.
This error occurs because LIMIT is not a valid SQL keyword for most databases. In MySQL, the correct keyword is LIMIT 1, while in SQL Server, it is TOP 1.
Therefore, the corrected code would be:
private void LastRecord() { 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()) { ... // Remaining code } }
The above is the detailed content of How Do I Select the Last Record from an SQL Table?. For more information, please follow other related articles on the PHP Chinese website!