Retrieve last row inserted into table with non sequential primary key – MySql

Posted on

Question :

Is it possible to know which last row was inserted into a MySql table where the primary key is not sequential?

I have a table where the primary key is made up of two columns that are FK, so they do not follow a sequence.

When executed the query select last_insert_id(); is returned 0 (It makes sense, because no ID has been entered anyway).

The best way out is to put a same ID column?

    

Answer :

Add a column with the insertion date:

ALTER TABLE tabela ADD insercao DATETIME DEFAULT CURRENT_TIMESTAMP;

Or an auto-increment id:

ALTER TABLE tabela ADD id INTEGER NOT NULL AUTO_INCREMENT;

    

Leave a Reply

Your email address will not be published. Required fields are marked *