Search code examples
mysqlmysql-workbenchlast-insert-id

How to select last_insert_id?


I have an SQL statement that returns more than one value: enter image description here

In my code I then need to call the last ID that was inserted. I have seen some examples about SELECT LAST_INSERT_ID() but they all seems to be for insert statements. I just want to show the last inserted id.

So from the image below I would only need to select ID 13.


Solution

  • Use ORDER BY and LIMIT .

    Query

    SELECT dl.* FROM driver_log dl
    WHERE dl.Company_ID = 76 AND dl.Manifesr=tNo = 8199
    ORDER BY ID DESC LIMIT 1;
    

    If you want to select only the ID, then use MAX function.

    SELECT MAX(dl.ID) as ID 
    FROM driver_log dl
    WHERE dl.Company_ID = 76 AND dl.Manifesr=tNo = 8199;