223

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());
    }
}
Tassisto
  • 9,877
  • 28
  • 100
  • 157

17 Answers17

512

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
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
72

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!

Ricardo Fercher
  • 917
  • 6
  • 10
  • 7
    Works completely fine with oracle too and is faster than sorting – MaKiPL Feb 05 '18 at 10:09
  • Does it works for lexicographically the column, means I stored the date in string format, now I want to retrieve the last message sent, so I want to fetch it. – Manav Sarkar Jun 17 '22 at 15:18
27

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.

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
18
SELECT * FROM TABLE ORDER BY ID DESC LIMIT 1

Yes this is mysql, SQL Server:

SELECT TOP 1 * FROM Table ORDER BY ID DESC
Simon
  • 9,197
  • 13
  • 72
  • 115
12

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

jarlh
  • 42,561
  • 8
  • 45
  • 63
9

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 
Jenna Leaf
  • 2,255
  • 21
  • 29
7

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)

Bostone
  • 36,858
  • 39
  • 167
  • 227
6

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;
Adrian
  • 744
  • 7
  • 17
5
SELECT * FROM table ORDER BY Id DESC LIMIT 1
2

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

jeje
  • 3,191
  • 3
  • 26
  • 41
2

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.

Pow-Ian
  • 3,607
  • 1
  • 22
  • 31
  • If there is no proper element to order on, you could return any record. A 'last' record has to refer to a certain order right? – Herbert Van-Vliet Sep 29 '22 at 07:24
  • @HerbertVan-Vliet Your assertion is 100% accurate. I am arguing that if you 'need' rows to have an order, you can get an arbitrary order and using that arbitrary order, you can then get the 'last' row. This feels like a philosophical question because without any order, every element is the nth element of a collection. The OP was looking for how to get the 'last record' of a table with a key, and there are great answers here on how to do that. I however landed here while trying to get an arbitrary 'last record' and so I shared my solution. – Pow-Ian Sep 29 '22 at 12:26
0

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.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
GeeDee
  • 11
  • 2
0
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
Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
  • 1
    Welcome to stackoverflow. In addition to the answer you've provided, please consider providing a brief explanation of why and how this fixes the issue. – jtate Mar 08 '19 at 15:16
-1

I think this should do it.

declare @x int;
select @x = max(id) from table_name;
select * from where id = @x;
lizardkingLK
  • 25
  • 2
  • 8
-2
$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);
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • did you read the question carefully? how does `INSERT`'ing a new value relate to "how to select the last record of that table"? – landru27 Nov 11 '18 at 21:00
  • 2
    Welcome to Stack Overflow! Thank you for the code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its [long-term value](https://meta.stackexchange.com/q/114762/206345) by describing why this is a good solution to the problem, and would make it more useful to future readers with other similar questions. Please edit your answer to add some explanation, including the assumptions you've made. – sepehr Nov 12 '18 at 00:02
  • Don't write php specific code when OP has asked about SQL language only. – Steve Moretz Feb 08 '19 at 08:53
-2

You can also do something like this:

SELECT LAST (column_name) AS LAST_CUSTOMER FROM table_name;

vikas95prasad
  • 1,234
  • 1
  • 12
  • 37
  • 1
    You should note that the last() function is only supported in MS Access https://www.javatpoint.com/sql-select-last – malik masis Jun 03 '20 at 08:56
-4

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`
VipinKG
  • 11
  • 3