get primay key of inserted row in mysql

How to Get Primary Key of Newly Inserted Row in MySQL

MySQL allows you to easily insert rows into your tables. In most tables, each row has a primary key consisting of one more or more columns, to uniquely identify each row. Sometimes you may need to get primary key of newly inserted row in MySQL. Here are the steps to do it.


How to Get Primary Key of Newly Inserted Row in MySQL

It is quite easy to get primary key of newly added row in MySQL. Let us say you have run the following INSERT query.

INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);

Just run the following query to get primary key of newly inserted row in MySQL.

SELECT LAST_INSERT_ID();

The above query will get you the primary key of last row that you inserted. Please note, this value is maintained by MySQL server on a per-connection basis. In other words, if two different users simultaneously insert new row in MySQL table, then it will return the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client.

The value returned by LAST_INSERT_ID() is per user and unaffected by other queries run by other users on the server.

In this short article, we have learnt how to get primary key of latest inserted row in MySQL.

Also read:

How to Find Tables With Column Names in MySQL
How to Find my.cnf File Location in MySQL
How to Add Option to Select Using jQuery
How to Use JavaScript Variables in jQuery Selectors
How to Select Element With Multiple Classes in jQuery

Leave a Reply

Your email address will not be published.