[sql] How to select the last record of a table in SQL?

This is a sample code to select all records from a table. Can someone show me how to select the last record of that table?

select * from table

When I use: SELECT * FROM TABLE ORDER BY ID DESC LIMIT I get this error: Line 1: Incorrect syntax near 'LIMIT'. This is the code I use:

private void LastRecord()
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HELPDESK_OUTLOOKConnectionString3"].ToString());

    conn.Open();
    SqlDataReader myReader = null;
    SqlCommand myCommand = new SqlCommand("SELECT * FROM HD_AANVRAGEN ORDER BY " +
                "aanvraag_id DESC LIMIT 1", conn);
    myReader = myCommand.ExecuteReader();
    while (myReader.Read())
    {
        TextBox1.Text = (myReader["aanvraag_id"].ToString());
        TextBox1.Text += (myReader["wijziging_nummer"].ToString());
        TextBox1.Text += (myReader["melding_id"].ToString());
        TextBox1.Text += (myReader["aanvraag_titel"].ToString());
        TextBox1.Text += (myReader["aanvraag_omschrijving"].ToString());
        TextBox1.Text += (myReader["doorlooptijd_id"].ToString());
        TextBox1.Text += (myReader["rapporteren"].ToString());
        TextBox1.Text += (myReader["werknemer_id"].ToString());
        TextBox1.Text += (myReader["outlook_id"].ToString());
    }
}

This question is related to sql sql-server sql-server-2008

The answer is


to get the last row of a SQL-Database use this sql string:

SELECT * FROM TableName WHERE id=(SELECT max(id) FROM TableName);

Output:

Last Line of your db!


It is always a good practice in your table design to have an automatic row identifier, such as

 [RowID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL

, then you can identify your last row by

 select * from yourTable where rowID =  @@IDENTITY 

SELECT * FROM table ORDER BY Id DESC LIMIT 1

select ADU.itemid, ADU.startdate, internalcostprice 
from ADUITEMINTERNALCOSTPRICE ADU

right join

   (select max(STARTDATE) as Max_date, itemid 
   from ADUITEMINTERNALCOSTPRICE
   group by itemid) as A

on A.ITEMID = ADU.ITEMID
and startdate= Max_date

You can also do something like this:

SELECT LAST (column_name) AS LAST_CUSTOMER FROM table_name;


The last is just the first when you reverse your ordering.


In Oracle, you can do:

SELECT *
FROM (SELECT EMP.*,ROWNUM FROM EMP ORDER BY ROWNUM DESC)
WHERE ROWNUM=1;

This is one of the possible ways.


I upvoted Ricardo. Actually max is much efficient than sorting . See the differences. its excellent.

I had to get the last row/update record (timeStamp)

`sqlite> select timeStamp from mypadatav2 order by timeStamp desc limit 1;
 2020-03-11 23:55:00
 Run Time: real 1.806 user 1.689242 sys 0.117062`

`sqlite> select max(timeStamp) from mypadatav2;
 2020-03-11 23:55:00
 Run Time: real 0.553 user 0.412618 sys 0.134340`

I think this should do it.

declare @x int;
select @x = max(id) from table_name;
select * from where id = @x;

MS SQL Server has supported ANSI SQL FETCH FIRST for many years now:

SELECT * FROM TABLE
ORDER BY ID DESC 
OFFSET 0 ROWS FETCH FIRST 1 ROW ONLY

(Works with most modern databases.)


Assuming you have an Id column:

SELECT TOP 1 *
  FROM table
 ORDER
    BY Id DESC;

Also, this will work on SQL Server. I think that MySQL you might need to use:

SELECT *
  FROM table
 ORDER
    BY Id DESC
 LIMIT 1

But, I'm not 100% sure about this.

EDIT

Looking at the other answers, I'm now 100% confident that I'm correct with the MySQL statement :o)

EDIT

Just seen your latest comment. You could do:

SELECT MAX(Id)
  FROM table

This will get you the highest Id number.


Almost all answers assume the ID column is ordered (and perhaps auto incremented). There are situations, however, when the ID column is not ordered, hence the ORDER BY statement makes no sense.

The last inserted ID might not always be the highest ID, it is just the last (unique) entry.

One possible solution for such a situation is to create a row id on the fly:

SET @r = 0;
SELECT * FROM (SELECT *, (@r := @r + 1) AS r_id FROM uat3187) AS tmp
    ORDER BY r_id DESC LIMIT 1;

If you have a self-incrementing field (say ID) then you can do something like: SELECT * FROM foo WHERE ID = (SELECT max(ID) FROM foo)


$sql="SELECT tot_visit FROM visitors WHERE date = DATE(NOW()) - 1 into @s                
$conn->query($sql);
$sql = "INSERT INTO visitors (nbvisit_day,date,tot_visit) VALUES (1,CURRENT_DATE,@s+1)";
$conn->query($sql);

SELECT * FROM TABLE ORDER BY ID DESC LIMIT 1

Yes this is mysql, SQL Server:

SELECT TOP 1 * FROM Table ORDER BY ID DESC

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?