Good day.

I insert data (which, perhaps, is already repeated in the table), and they are assigned the key id. How can I get the id of the string in the next query in order to work with the id further?
Thank!

  • What are you doing sql queries through? Perhaps the new id is already available and can be obtained without additional requests. For example, I know in php in mysqli there is a mysql_insert_id in which the id generated by the last INSERT query is stored - IVsevolod
  • Maybe I didn’t understand the question, but why aren't SELECT id FROM table_name ORDER BY id DESC LIMIT 1 satisfied? - dzukp
  • @ Roman Rakzin, what kind of DBMS? SQL is quite different from place to place. @dzukp, this is not a very reliable way. Depending on the isolation level of the transaction, it may work, or it may lie. - Nofate
  • DESC LIMIT 1 - I thought too. But if we assume that another person sends a friend to these fractions of seconds - then it will be done - Rakzin Roman
  • @TwoRS that is why it is impossible to do this, the correct answer has already been given below - AntonioK

2 answers 2

MySQL LAST_INSERT_ID ()

PostgreSQL Add RETURNING "FILE_NAME" to the query and you will get back the value of the FILE_NAME field of the new record.

    In MS SQL, for example:

    • select scope_identity() to get the last id created in the current connection and only the current scope (triggers and functions are ignored).
    • select @@identity to get the last id created on the current connection regardless of the scope (triggers and functions are taken into account).
    • select ident_curent('tablename') to get the last id on a specific table created on any connection.