Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Inserting a row and returning primary key

I have inserted a row with some data in a table where a primary key is present. How would one "SELECT" the primary key of the row one just inserted?

I should have been more specific and mentioned that I'm currently using SQLite.

like image 500
Samuel Moriarty Avatar asked Dec 12 '11 18:12

Samuel Moriarty


People also ask

How do you find the primary key of an inserted record?

If you insert records into a table which contains auto-incremented column, using a Statement or, PreparedStatement objects. You can retrieve the values of that particular column, generated by them object using the getGeneratedKeys() method.

Can we add primary key after table creation?

Because a table can have only one primary key, you cannot add a primary key to a table that already has a primary key defined. To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.

How do I insert multiple rows with the same primary key?

The whole idea of a primary key is to have a unique identifier for each row, so you can not do that. However, if you want a way of grouping rows, you can either add a group column to your table, or create a table for the grouping. For example group_members and have that contain two columns, "group_id" and "row_id".


2 Answers

For MS SQL Server:

SCOPE_IDENTITY() will return you the last generated identity value within your current scope:

SELECT SCOPE_IDENTITY() AS NewID 
like image 55
Michael Fredrickson Avatar answered Oct 07 '22 15:10

Michael Fredrickson


For SQL Server 2005 and up, and regardless of what type your primary key is, you could always use the OUTPUT clause to return the values inserted:

INSERT INTO dbo.YourTable(col1, col2, ...., colN) OUTPUT Inserted.PrimaryKey VALUES(val1, val2, ....., valN) 
like image 35
marc_s Avatar answered Oct 07 '22 17:10

marc_s