0

I have two tables in my databaes: original_db and archive_db.

in original_db I have two cols:

  1. id (auto-increment)
  2. name

in archive_db I have three cols:

  1. id (auto-increment)
  2. user_id
  3. name

I want to copy original_db to archive_db when user_id is let's say '1'

sql query:

INSERT INTO archive_db (user_id, name)
SELECT '1', name FROM original_db

After query this at first time everything is ok. So I Have archive_db:

  1. id (auto-increment) [1,2,3]
  2. user_id [1,1,1]
  3. name [nam1,name2,name3]

but when I do again this query with another user_id let's say '2':

    INSERT INTO archive_db (user_id, name)
    SELECT '2', name FROM original_db

I get this archive_db table:

  1. id (auto-increment) [1, 2, 3, 7, 8, 9]
  2. user_id [1, 1, 1, 2, 2, 2]
  3. name [name1, name2, name3, name1, name2, name3]

Why the id has the wrong autoincrementation, it should be 1,2,3,4,5,6

4
  • 2
    Its really helpful if you dont name tables with the word database or db. Databases hold tables and tables hold rows.
    – RiggsFolly
    Jan 27, 2022 at 16:12
  • 2
    A variety of things could cause this to happen, such as an abandoned transaction or some internal optimization of some kind. There's no guarantee that auto-increment values will always be sequential with no gaps. It's merely guaranteed to be unique and always a larger number than previously inserted records. It's not really a problem, it's just a behavior of that functionality. (I bet there's a duplicate question which explains this in depth, I just haven't found it.)
    – David
    Jan 27, 2022 at 16:14
  • 3
    Your select query is not limited to one row it is getting ALL the current rows in the table, this one SELECT '1', name FROM original_db and this one SELECT '2', name FROM original_db you would need to add a WHERE clause like SELECT id, name FROM original_db WHERE id = 1
    – RiggsFolly
    Jan 27, 2022 at 16:15
  • What table types and AUTO_INCREMENT Lock Modes are you using? see also dev.mysql.com/doc/refman/8.0/en/… Jan 29, 2022 at 11:19

1 Answer 1

1

And didn't 3 rows be deleted during the test? Then just set autoincrement: ALTER TABLE archive_db AUTO_INCREMENT = 4;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.