Click here to Skip to main content
15,901,505 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
i want last row from the database so which query should i write for that?
Posted

GET last record in a SQL database:

SELECT *
FROM TABLE
WHERE ID = (SELECT MAX(ID) FROM TABLE)


or

select top 1 * from TABLE_NAME order by ID desc
 
Share this answer
 
Comments
Herman<T>.Instance 22-Nov-12 6:12am    
My 5! because ou use the index for the Order by desc, Max() function takes more time
Hi Sumit,

This is depend on your database type.

If you have a primary ke in your table with auto increment then use below query.
SQL
Select * From tableName Where PK = (Select Max(PK) From tableName)

If you are using MySql then use below query.
C#
SELECT * FROM tableName WHERE id = LAST_INSERT_ID( );

If you are using ORALCE then use below query.
C#
SELECT * FROM tableName where ROWID = (SELECT MAX(ROWID) FROM tableName);

Hope this will help you.
 
Share this answer
 
v2
Hello Sumit,

you have to use

SQL
SELECT SCOPE_IDENTITY() in sql server

SCOPE_IDENTITY returns the last inserted IDENTITY value in this current scope.
 
Share this answer
 
select * from table where id=(select Max(id) from table)


//if you have primary key with auto increment

select * from table where pk=(select Max(pk) from table)
 
Share this answer
 
SQL
SELECT *
FROM    TABLE
WHERE   ID = (SELECT MAX(ID)  FROM TABLE)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900