Home >Database >Mysql Tutorial >How Can I Efficiently Select the Last Record from an SQL Table?

How Can I Efficiently Select the Last Record from an SQL Table?

DDD
DDDOriginal
2025-01-06 01:29:39649browse

How Can I Efficiently Select the Last Record from an SQL Table?

Selecting the Last Record in a Table with SQL

In SQL, retrieving the last record from a table is a common task. This guide will walk you through various methods to achieve this.

One approach is to use the ORDER BY clause along with DESC to sort the records in descending order based on a specified column (ID in this example):

SQL Server

SELECT TOP 1 * FROM Table ORDER BY ID DESC

MySQL

SELECT * FROM Table ORDER BY ID DESC LIMIT 1

In C#, the code you provided for selecting the last record using LIMIT is incorrect. The correct syntax is:

SqlCommand myCommand = new SqlCommand("SELECT TOP 1 * FROM HD_AANVRAGEN ORDER BY aanvraag_id DESC", conn);

Here, we use TOP 1 in combination with the ORDER BY DESC clause to retrieve the last record.

Alternatively, you can use the below method to get the last record in a table:

SELECT * FROM Table WHERE ID IN (SELECT MAX(ID) FROM Table)

This query retrieves all records that match the maximum ID value in the table, effectively selecting the last record.

Remember to adjust the table and column names in all code and queries to match your actual database schema and requirements.

The above is the detailed content of How Can I Efficiently Select the Last Record from an SQL Table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn