Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safest way to get last record ID from a table

In SQL Server 2008 and higher what is the best/safest/most correct way

  1. to retrieve the ID (based on autoincrementing primary key) out of the database table?
  2. to retrieve the value of the last row of some other column (like, SELECT TOP 1 FROM Table ORDER BY DESC)?
like image 390
mare Avatar asked Aug 06 '10 08:08

mare


People also ask

How can I get the last record of a table?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How do I find the last ID of a SQL table?

How to get last inserted id of a MySQL table using LAST_INSERT_ID() We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.

How do you select last n records from a table?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.

Which method is used to display a last record from the database?

The LAST() function in Structured Query Language shows the last value from the specified column of the table.


1 Answers

SELECT IDENT_CURRENT('Table') 

You can use one of these examples:

SELECT * FROM Table  WHERE ID = (     SELECT IDENT_CURRENT('Table'))  SELECT * FROM Table WHERE ID = (     SELECT MAX(ID) FROM Table)  SELECT TOP 1 * FROM Table ORDER BY ID DESC 

But the first one will be more efficient because no index scan is needed (if you have index on Id column).

The second one solution is equivalent to the third (both of them need to scan table to get max id).

like image 130
gyromonotron Avatar answered Oct 14 '22 03:10

gyromonotron