How to fetch the last record from a database table?
3 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
ShankeyRank #972 · 2.1K reputationPosted Mar 8, 2011, 12:02 AM EST
Use CTE feature of SQL server as shown below to fetch last record of the table
with WITHROWID AS(
SELECT ROW_NUMBER() OVER(ORDER BY [StudentId]) AS RowID,[StudentId]
,[StudentName]
,[StudentAddress]
FROM [dbo].[Student])
SELECT TOP 1 * FROM WITHROWID ORDER BY RowID DESC
Hope it will help u and give you right direction .
Thanks,
Shankey
Shalini JunejaRank #351 · 7.1K reputationPosted Mar 8, 2011, 10:17 PM EST
If you want to fetch the last inserted inserted in a TABLE in a DATABASE that has an IDENTITY column named ID, you could use the following:
SELECT *
FROM TABLE
WHERE ID = IDENT_CURRENT('TABLE')
or
SELECT *
FROM TABLE
WHERE ID = (SELECT MAX(ID) FROM TABLE)
I hope this helps u in fatching last record
thanks
Shalini juneja
Deepak VermaRank #672 · 3.6K reputationPosted Mar 8, 2011, 11:20 PM EST
Use the following query -
SELECT * FROM Table_Name WHERE ROWID IN (SELECT MAX(ROWID) FROM Table_Name);
Note : I execute it in Oracle 10g only. This query will give you exactly the last record in a table even you arranged records in any order.