Let\'s say I have the following data in the Customers table: (nothing more)
ID FirstName LastName
-------------------------------
20 John Macken
If you're not using auto-incrementing fields, you can achieve a similar result with something like the following:
insert into Customers (ID, FirstName, LastName)
select max(ID)+1, 'Barack', 'Obama' from Customers;
This will ensure there's no chance of a race condition which could be caused by someone else inserting into the table between your extraction of the maximum ID and your insertion of the new record.
This is using standard SQL, there are no doubt better ways to achieve it with specific DBMS' but they're not necessarily portable (something we take very seriously in our shop).
To get it at any time, you can do SELECT MAX(Id) FROM Customers
.
In the procedure you add it in, however, you can also make use of SCOPE_IDENTITY
-- to get the id last added by that procedure.
This is safer, because it will guarantee you get your Id
--just in case others are being added to the database at the same time.
select * from tablename order by ID DESC
that will give you row with id 22
You can also use relational algebra. A bit lengthy procedure, but here it is just to understand how MAX() works:
E := πID (Table_Name)
E1 := πID (σID >= ID' ((ρID' E) ⋈ E)) – πID (σID < ID’ ((ρID' E) ⋈ E))
Your answer: Table_Name ⋈ E1
Basically what you do is subtract set of ordered relation(a,b) in which a<
b from A where a, b ∈ A.
For relation algebra symbols see: Relational algebra From Wikipedia
SELECT * FROM Customers ORDER BY ID DESC LIMIT 1
Then get the ID.
If you are using AUTOINCREMENT
, use:
SELECT LAST\_INSERT\_ID();
Assumming that you are using Mysql: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
Postgres handles this similarly via the currval(sequence_name)
function.
Note that using MAX(ID)
is not safe, unless you lock the table, since it's possible (in a simplified case) to have another insert that occurs before you call MAX(ID)
and you lose the id of the first insert. The functions above are session based so if another session inserts you still get the ID that you inserted.