None of these alternatives will retrieve the last ID.
Your code is to retrieve the Higher ID. Usually the last and the greatest coincide, but it is not an absolute truth.
To know the last ID automatically entered, the code is this:
SELECT LAST_INSERT_ID;
But keep in mind that only works if you last inserted in the same connection .
Not all flowers: If the last insert added 3 records in the DB, this function returns the first one, not the last one.
As you said it is a separate query, what can help is this query that returns the next automatic ID to be used:
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'nome da sua tabela'
AND table_schema = 'nome do seu DB' ;
But then, what's the problem with the question code?
If you really want to know the last inserted, the only safe feature is to recover the data with LAST_INSERT_ID
, or exaggerating, by doing a trigger for this.
For example, look at common situations where the question code will not return the last value entered:
-
If the last records are deleted, LAST_INSERT_ID
will still contain the value entered, but the question code will retrieve the IDs prior to these (which will not match those of the next inserts).
/ li>
-
If an insert is made by specifying an ID manually, smaller than the one entered, there is no sure way to know the last one.
Now, you have to think about something important: Depending on the use you are going to make, you do not really need the last inserted, but the existing one. In this case, the question code resolves.
Alternatively, you can use the SELECT AUTOINCREMENT
technique above, and subtract 1
to estimate what was the previous one. This also does not guarantee that it really was the last inserted, but is less likely to give side effects.
Another caution to take : It may well happen that some other transaction occurs in the DB, and this value changes before you use it, so anything that runs away from LAST_INSERT_ID
can generate race condition . Ideally, do not use the value for anything other than actually referencing the last line entered.
One more alert: (to make life even more complicated) you should only use LAST_INSERT_ID
if the last insertion did not give an error, otherwise it may be taking a previous insertion ID. There are people who test if they gave zero to see if they returned an ID or not, but this is not reliable if they do not check if INSERT
really succeeded. >
As for performance, the only way to be sure is to benchmark, because it depends on a number of factors.