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

SqlSql ServerSql Server-2008

Sql Problem Overview


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());
    }
}

Sql Solutions


Solution 1 - Sql

Without any further information, which Database etc the best we can do is something like

Sql Server

SELECT TOP 1 * FROM Table ORDER BY ID DESC

MySql

SELECT * FROM Table ORDER BY ID DESC LIMIT 1

Solution 2 - Sql

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!

Solution 3 - Sql

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.

Solution 4 - 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

Solution 5 - Sql

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.)

Solution 6 - Sql

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 

Solution 7 - Sql

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)

Solution 8 - Sql

SELECT * FROM table ORDER BY Id DESC LIMIT 1

Solution 9 - Sql

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 my_table) AS tmp
    ORDER BY r_id DESC LIMIT 1;

Solution 10 - Sql

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

Solution 11 - Sql

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.

Solution 12 - Sql

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

Solution 13 - Sql

If your table has no auto incremented value and otherwise has no good element to order on, you can get the arbitrary order of the items in any collection like this

SELECT
	[item]
FROM (
	SELECT
		*
		, ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY GETDATE()) 'RN'
	FROM [TABLE]
) RDR 
WHERE [RN] = (
	SELECT
		MAX([RN])
	FROM (
		SELECT
			*
			, ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY GETDATE()) 'RN'
		FROM [TABLE]
	) RDR 
)

An important caveat is that the performance for this is going to be abysmal with larger sets of data.

Solution 14 - Sql

I think this should do it.

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

Solution 15 - Sql

$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);

Solution 16 - Sql

You can also do something like this:

SELECT LAST (column_name) AS LAST_CUSTOMER FROM table_name;

Solution 17 - Sql

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`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTassistoView Question on Stackoverflow
Solution 1 - SqlAdriaan StanderView Answer on Stackoverflow
Solution 2 - SqlRicardo FercherView Answer on Stackoverflow
Solution 3 - SqlNeil KnightView Answer on Stackoverflow
Solution 4 - SqlSimonView Answer on Stackoverflow
Solution 5 - SqljarlhView Answer on Stackoverflow
Solution 6 - SqlJenna LeafView Answer on Stackoverflow
Solution 7 - SqlBostoneView Answer on Stackoverflow
Solution 8 - Sqluser142019View Answer on Stackoverflow
Solution 9 - SqlAdrianView Answer on Stackoverflow
Solution 10 - SqljejeView Answer on Stackoverflow
Solution 11 - SqlGeeDeeView Answer on Stackoverflow
Solution 12 - SqlPanjas51View Answer on Stackoverflow
Solution 13 - SqlPow-IanView Answer on Stackoverflow
Solution 14 - SqlChanuka FernandoView Answer on Stackoverflow
Solution 15 - SqlHani ChararaView Answer on Stackoverflow
Solution 16 - Sqlvikas95prasadView Answer on Stackoverflow
Solution 17 - SqlVipinKGView Answer on Stackoverflow