Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get last inserted id of a NON - auto incremented column in MySQL?

Tags:

mysql

I know how LAST_INSERT_ID() works for auto incremented columns, but I cannot find a way to get the last id I inserted for a non auto incremented column.

Is there a way I can do that?

like image 445
Guiness Avatar asked Jan 05 '12 16:01

Guiness


People also ask

How do I get the last row inserted id in MySQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.

How do you find out which auto increment was assigned on the last insert?

Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function.

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

How do I get the last insert ID from a specific 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.


2 Answers

you can easily do that using the same LAST_INSERT_ID().

INSERT INTO thetable (id, value)
VALUES (LAST_INSERT_ID(126), 'some data');

SELECT LAST_INSERT_ID();  -- returns 126
like image 197
newtover Avatar answered Oct 08 '22 22:10

newtover


I'm assuming you want the retrieve this last inserted id at some later point after inserting it, since if you need it right after inserting it you obviously would already know what the id is.

The only way you'll be able to get that is to have another column on the table that can indicate which row was last inserted, such as a timestamp or datetime column. If your ids are unique and increasing, you can just use that column. Then you just select 1 row ordered by that column in descending order.

For example

INSERT INTO my_table (id, timestamp) VALUES (123, NOW())

SELECT id FROM my_table ORDER BY timestamp DESC LIMIT 1

Edit: as per the comments below, you're much better off using an AUTO_INCREMENT column, though this column doesn't have to be the id column, you could add an auto-increment insert_order column of type Int and simply order by that.

like image 23
Dan Simon Avatar answered Oct 08 '22 22:10

Dan Simon