ON DUPLICATE KEY + AUTO INCREMENT issue mysqlHow to update a row and insert one if it doesn't exist, without wrongly raising auto_incrementAdding second index broke auto increment on primary keyPDO avoid gaps when using ON DUPLICATE UPDATEMySQL INSERT …ON DUPLICATE UPDATE - Adds one to the autoincrementHow to use update all, when all records are different?MySql upsert and auto-increment causes gapsInsert into on duplicate key - auto increment id skippedinsert on duplicate key update with two contitionsClean auto increment on primary key with multiple indexesShould I use the datetime or timestamp data type in MySQL?“INSERT IGNORE” vs “INSERT … ON DUPLICATE KEY UPDATE”Finding duplicate values in MySQLPHP/MySQL insert row then get 'id'MySQL INSERT … SELECT… ON DUPLICATE KEY UPDATE incrementPrevent auto increment on MySQL duplicate insertMySQL Delete all rows from table and reset ID to zeroMySQL Auto increment not incrementingCodeigniter on duplicate key update with auto increment in MySQLMySQL incrementing Primary Key on INSERT INTO .. ON DUPLICATE KEY UPDATE

Can one be a co-translator of a book, if he does not know the language that the book is translated into?

What is the intuition behind short exact sequences of groups; in particular, what is the intuition behind group extensions?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Twin primes whose sum is a cube

When a company launches a new product do they "come out" with a new product or do they "come up" with a new product?

Were any external disk drives stacked vertically?

How can I make my BBEG immortal short of making them a Lich or Vampire?

Is it possible to run Internet Explorer on OS X El Capitan?

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?

Why is the 'in' operator throwing an error with a string literal instead of logging false?

Is it canonical bit space?

1960's book about a plague that kills all white people

What's the point of deactivating Num Lock on login screens?

What killed these X2 caps?

How can saying a song's name be a copyright violation?

AES: Why is it a good practice to use only the first 16bytes of a hash for encryption?

Why is Collection not simply treated as Collection<?>

What is the word for reserving something for yourself before others do?

Blender 2.8 I can't see vertices, edges or faces in edit mode

Is it legal for company to use my work email to pretend I still work there?

Did Shadowfax go to Valinor?

Combinations of multiple lists

Took a trip to a parallel universe, need help deciphering

Should I tell management that I intend to leave due to bad software development practices?



ON DUPLICATE KEY + AUTO INCREMENT issue mysql


How to update a row and insert one if it doesn't exist, without wrongly raising auto_incrementAdding second index broke auto increment on primary keyPDO avoid gaps when using ON DUPLICATE UPDATEMySQL INSERT …ON DUPLICATE UPDATE - Adds one to the autoincrementHow to use update all, when all records are different?MySql upsert and auto-increment causes gapsInsert into on duplicate key - auto increment id skippedinsert on duplicate key update with two contitionsClean auto increment on primary key with multiple indexesShould I use the datetime or timestamp data type in MySQL?“INSERT IGNORE” vs “INSERT … ON DUPLICATE KEY UPDATE”Finding duplicate values in MySQLPHP/MySQL insert row then get 'id'MySQL INSERT … SELECT… ON DUPLICATE KEY UPDATE incrementPrevent auto increment on MySQL duplicate insertMySQL Delete all rows from table and reset ID to zeroMySQL Auto increment not incrementingCodeigniter on duplicate key update with auto increment in MySQLMySQL incrementing Primary Key on INSERT INTO .. ON DUPLICATE KEY UPDATE






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








19















I have table structure like this



enter image description here



when I insert row to the table I'm using this query:



INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE id = id, material_item = data, ... hidden = data;



when I first insert data without triggering the ON DUPLICATE KEY the id increments fine:



enter image description here



but when the ON DUPLICATE KEY triggers and i INSERT A NEW ROW the id looks odd to me:



enter image description here



How can I keep the auto increment, increment properly even when it triggers ON DUPLICATE KEY?










share|improve this question
























  • Most questions here with concerns about gaps in AUTO_INCREMENT sequence are the result of using it for the wrong task. It it's only curiosity, then it's fine :)

    – Álvaro González
    May 7 '14 at 11:52











  • @ÁlvaroG.Vicario did I miss use the AUTO_INCREMENT?

    – newbie
    May 7 '14 at 11:55






  • 1





    possible duplicate of MySQL INSERT ....ON DUPLICATE UPDATE - Adds one to the autoincrement

    – Álvaro González
    May 7 '14 at 11:55











  • I don't know. Are gaps a problem?

    – Álvaro González
    May 7 '14 at 11:55






  • 1





    @ÁlvaroG.Vicario Not really but I just want it to increment properly because it might be useful in the future development

    – newbie
    May 7 '14 at 11:59

















19















I have table structure like this



enter image description here



when I insert row to the table I'm using this query:



INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE id = id, material_item = data, ... hidden = data;



when I first insert data without triggering the ON DUPLICATE KEY the id increments fine:



enter image description here



but when the ON DUPLICATE KEY triggers and i INSERT A NEW ROW the id looks odd to me:



enter image description here



How can I keep the auto increment, increment properly even when it triggers ON DUPLICATE KEY?










share|improve this question
























  • Most questions here with concerns about gaps in AUTO_INCREMENT sequence are the result of using it for the wrong task. It it's only curiosity, then it's fine :)

    – Álvaro González
    May 7 '14 at 11:52











  • @ÁlvaroG.Vicario did I miss use the AUTO_INCREMENT?

    – newbie
    May 7 '14 at 11:55






  • 1





    possible duplicate of MySQL INSERT ....ON DUPLICATE UPDATE - Adds one to the autoincrement

    – Álvaro González
    May 7 '14 at 11:55











  • I don't know. Are gaps a problem?

    – Álvaro González
    May 7 '14 at 11:55






  • 1





    @ÁlvaroG.Vicario Not really but I just want it to increment properly because it might be useful in the future development

    – newbie
    May 7 '14 at 11:59













19












19








19


4






I have table structure like this



enter image description here



when I insert row to the table I'm using this query:



INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE id = id, material_item = data, ... hidden = data;



when I first insert data without triggering the ON DUPLICATE KEY the id increments fine:



enter image description here



but when the ON DUPLICATE KEY triggers and i INSERT A NEW ROW the id looks odd to me:



enter image description here



How can I keep the auto increment, increment properly even when it triggers ON DUPLICATE KEY?










share|improve this question
















I have table structure like this



enter image description here



when I insert row to the table I'm using this query:



INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE id = id, material_item = data, ... hidden = data;



when I first insert data without triggering the ON DUPLICATE KEY the id increments fine:



enter image description here



but when the ON DUPLICATE KEY triggers and i INSERT A NEW ROW the id looks odd to me:



enter image description here



How can I keep the auto increment, increment properly even when it triggers ON DUPLICATE KEY?







mysql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 7 '14 at 11:50









Arslan Ali

13.3k63856




13.3k63856










asked May 7 '14 at 11:46









newbienewbie

78062045




78062045












  • Most questions here with concerns about gaps in AUTO_INCREMENT sequence are the result of using it for the wrong task. It it's only curiosity, then it's fine :)

    – Álvaro González
    May 7 '14 at 11:52











  • @ÁlvaroG.Vicario did I miss use the AUTO_INCREMENT?

    – newbie
    May 7 '14 at 11:55






  • 1





    possible duplicate of MySQL INSERT ....ON DUPLICATE UPDATE - Adds one to the autoincrement

    – Álvaro González
    May 7 '14 at 11:55











  • I don't know. Are gaps a problem?

    – Álvaro González
    May 7 '14 at 11:55






  • 1





    @ÁlvaroG.Vicario Not really but I just want it to increment properly because it might be useful in the future development

    – newbie
    May 7 '14 at 11:59

















  • Most questions here with concerns about gaps in AUTO_INCREMENT sequence are the result of using it for the wrong task. It it's only curiosity, then it's fine :)

    – Álvaro González
    May 7 '14 at 11:52











  • @ÁlvaroG.Vicario did I miss use the AUTO_INCREMENT?

    – newbie
    May 7 '14 at 11:55






  • 1





    possible duplicate of MySQL INSERT ....ON DUPLICATE UPDATE - Adds one to the autoincrement

    – Álvaro González
    May 7 '14 at 11:55











  • I don't know. Are gaps a problem?

    – Álvaro González
    May 7 '14 at 11:55






  • 1





    @ÁlvaroG.Vicario Not really but I just want it to increment properly because it might be useful in the future development

    – newbie
    May 7 '14 at 11:59
















Most questions here with concerns about gaps in AUTO_INCREMENT sequence are the result of using it for the wrong task. It it's only curiosity, then it's fine :)

– Álvaro González
May 7 '14 at 11:52





Most questions here with concerns about gaps in AUTO_INCREMENT sequence are the result of using it for the wrong task. It it's only curiosity, then it's fine :)

– Álvaro González
May 7 '14 at 11:52













@ÁlvaroG.Vicario did I miss use the AUTO_INCREMENT?

– newbie
May 7 '14 at 11:55





@ÁlvaroG.Vicario did I miss use the AUTO_INCREMENT?

– newbie
May 7 '14 at 11:55




1




1





possible duplicate of MySQL INSERT ....ON DUPLICATE UPDATE - Adds one to the autoincrement

– Álvaro González
May 7 '14 at 11:55





possible duplicate of MySQL INSERT ....ON DUPLICATE UPDATE - Adds one to the autoincrement

– Álvaro González
May 7 '14 at 11:55













I don't know. Are gaps a problem?

– Álvaro González
May 7 '14 at 11:55





I don't know. Are gaps a problem?

– Álvaro González
May 7 '14 at 11:55




1




1





@ÁlvaroG.Vicario Not really but I just want it to increment properly because it might be useful in the future development

– newbie
May 7 '14 at 11:59





@ÁlvaroG.Vicario Not really but I just want it to increment properly because it might be useful in the future development

– newbie
May 7 '14 at 11:59












3 Answers
3






active

oldest

votes


















35














This behavior is documented:




If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL
performs an UPDATE of the old row. For example, if column a is
declared as UNIQUE and contains the value 1, the following two
statements have similar effect:



 INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

UPDATE table SET c=c+1 WHERE a=1;


(The effects are not identical for
an InnoDB table where a is an auto-increment column. With an
auto-increment column, an INSERT statement increases the
auto-increment value but UPDATE does not.)




Here is a simple explanation. MySQL attempts to do the insert first. This is when the id gets auto incremented. Once increment, it stays. Then the duplicate is detected and the update happens. But the value gets missed.



You should not depend on auto_increment having no gaps. If that is a requirement, the overhead on the updates and inserts is much larger. Essentially, you need to put a lock on the entire table, and renumber everything that needs to be renumbered, typically using a trigger. A better solution is to calculate incremental values on output.






share|improve this answer


















  • 1





    +1. Well said. Thanks for including the actual documentation. ;-)

    – ghoti
    May 7 '14 at 12:01











  • If auto_increment isn't a requirement do you think the gap is ok?

    – newbie
    May 7 '14 at 12:15






  • 12





    This is stupid issue with mysql. Ok, I don't relay on it to be without gaps, but today I got hit limit of 16000000+ row (MEDIUMINT) when I have only around 500000 records which got often updated. Problem is that I have another tables with goes beyond 250Gb of size linked to this one - and to update it to INT (and loose storage space when its totally unneeded) takes days.

    – lapkritinis
    Mar 27 '17 at 9:59







  • 3





    I don't understand the reasoning behind this design. While I don't mind the gaps, I see no reason for the autoincrementation to occur as the ID never existed, so it just creates a lot of garbage IDs for nothing.

    – jsmars
    Feb 26 '18 at 13:52






  • 1





    I'm updating multiple records regularly using ON DUPLICATE KEY UPDATE . I don't care for the gaps but I fear from hitting the max column value. will using ALTER TABLE table_name AUTO_INCREMENT=1 (which resets the auto_increment to the last rows id + 1) regularly after each batch update be a bad practice?

    – David Avikasis
    Oct 3 '18 at 21:48


















1














I had the same frustration and I have a solution.



Let me first talk about "overheads". When I first wrote my DB update code, it did so many separate queries that it took 5 hours. Once I put on "ON DUPLICATE KEY UPDATE" I got it down to about 50 seconds. Amazing! Anyway the way I solved it means I have to do 2 queries, so instead of 1 minute I'm extending it to 2 minutes which I think is a fair cost considering.



First I did a standard sql query with data that had updates and inserts, but I included "IGNORE" so this just bypasses the updates and only inserts the new stuff.
"INSERT IGNORE INTO mytablename(stuff,stuff2) VALUES " -without the on duplicate key update. This means all the new records get put in. These new records wont break the auto_increment yet.



Next I did the "ON DUPLICATE KEY UPDATE" version of that sql statement, now this breaks the auto_increment value, but all the updates and inserts we've put in are all perfect auto_incrememnt values. It's just the next new record we add will be wrong...



So lastly you just patch up the mess by this sql:
"ALTER TABLE mytablename AUTO_INCREMENT = " . ($TableCount + 1);



remember to actually set $TableCount to the table count, then we add 1 and that's ready for when the next record gets written.



This is cheap and dirty but I like it. Make sure you don't write to the database at the same time using another function etc, because it could give errors. I think there is a way to lock the table? But I don't need that in my case.






share|improve this answer
































    -1














    INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE material_item = data, ... hidden = data



    Yes remove the ID=ID as it will automaticly add where PRIMARY KEY = PRIMARY KEY...






    share|improve this answer


















    • 1





      but what if it has duplicate key it will increment right?

      – newbie
      May 7 '14 at 11:53











    • It will not if your table is MyISSAM, on InnoDB it will. There are other ways to fix the issue on InnoDB

      – Seti
      May 7 '14 at 11:58











    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23516958%2fon-duplicate-key-auto-increment-issue-mysql%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    35














    This behavior is documented:




    If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
    would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL
    performs an UPDATE of the old row. For example, if column a is
    declared as UNIQUE and contains the value 1, the following two
    statements have similar effect:



     INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

    UPDATE table SET c=c+1 WHERE a=1;


    (The effects are not identical for
    an InnoDB table where a is an auto-increment column. With an
    auto-increment column, an INSERT statement increases the
    auto-increment value but UPDATE does not.)




    Here is a simple explanation. MySQL attempts to do the insert first. This is when the id gets auto incremented. Once increment, it stays. Then the duplicate is detected and the update happens. But the value gets missed.



    You should not depend on auto_increment having no gaps. If that is a requirement, the overhead on the updates and inserts is much larger. Essentially, you need to put a lock on the entire table, and renumber everything that needs to be renumbered, typically using a trigger. A better solution is to calculate incremental values on output.






    share|improve this answer


















    • 1





      +1. Well said. Thanks for including the actual documentation. ;-)

      – ghoti
      May 7 '14 at 12:01











    • If auto_increment isn't a requirement do you think the gap is ok?

      – newbie
      May 7 '14 at 12:15






    • 12





      This is stupid issue with mysql. Ok, I don't relay on it to be without gaps, but today I got hit limit of 16000000+ row (MEDIUMINT) when I have only around 500000 records which got often updated. Problem is that I have another tables with goes beyond 250Gb of size linked to this one - and to update it to INT (and loose storage space when its totally unneeded) takes days.

      – lapkritinis
      Mar 27 '17 at 9:59







    • 3





      I don't understand the reasoning behind this design. While I don't mind the gaps, I see no reason for the autoincrementation to occur as the ID never existed, so it just creates a lot of garbage IDs for nothing.

      – jsmars
      Feb 26 '18 at 13:52






    • 1





      I'm updating multiple records regularly using ON DUPLICATE KEY UPDATE . I don't care for the gaps but I fear from hitting the max column value. will using ALTER TABLE table_name AUTO_INCREMENT=1 (which resets the auto_increment to the last rows id + 1) regularly after each batch update be a bad practice?

      – David Avikasis
      Oct 3 '18 at 21:48















    35














    This behavior is documented:




    If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
    would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL
    performs an UPDATE of the old row. For example, if column a is
    declared as UNIQUE and contains the value 1, the following two
    statements have similar effect:



     INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

    UPDATE table SET c=c+1 WHERE a=1;


    (The effects are not identical for
    an InnoDB table where a is an auto-increment column. With an
    auto-increment column, an INSERT statement increases the
    auto-increment value but UPDATE does not.)




    Here is a simple explanation. MySQL attempts to do the insert first. This is when the id gets auto incremented. Once increment, it stays. Then the duplicate is detected and the update happens. But the value gets missed.



    You should not depend on auto_increment having no gaps. If that is a requirement, the overhead on the updates and inserts is much larger. Essentially, you need to put a lock on the entire table, and renumber everything that needs to be renumbered, typically using a trigger. A better solution is to calculate incremental values on output.






    share|improve this answer


















    • 1





      +1. Well said. Thanks for including the actual documentation. ;-)

      – ghoti
      May 7 '14 at 12:01











    • If auto_increment isn't a requirement do you think the gap is ok?

      – newbie
      May 7 '14 at 12:15






    • 12





      This is stupid issue with mysql. Ok, I don't relay on it to be without gaps, but today I got hit limit of 16000000+ row (MEDIUMINT) when I have only around 500000 records which got often updated. Problem is that I have another tables with goes beyond 250Gb of size linked to this one - and to update it to INT (and loose storage space when its totally unneeded) takes days.

      – lapkritinis
      Mar 27 '17 at 9:59







    • 3





      I don't understand the reasoning behind this design. While I don't mind the gaps, I see no reason for the autoincrementation to occur as the ID never existed, so it just creates a lot of garbage IDs for nothing.

      – jsmars
      Feb 26 '18 at 13:52






    • 1





      I'm updating multiple records regularly using ON DUPLICATE KEY UPDATE . I don't care for the gaps but I fear from hitting the max column value. will using ALTER TABLE table_name AUTO_INCREMENT=1 (which resets the auto_increment to the last rows id + 1) regularly after each batch update be a bad practice?

      – David Avikasis
      Oct 3 '18 at 21:48













    35












    35








    35







    This behavior is documented:




    If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
    would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL
    performs an UPDATE of the old row. For example, if column a is
    declared as UNIQUE and contains the value 1, the following two
    statements have similar effect:



     INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

    UPDATE table SET c=c+1 WHERE a=1;


    (The effects are not identical for
    an InnoDB table where a is an auto-increment column. With an
    auto-increment column, an INSERT statement increases the
    auto-increment value but UPDATE does not.)




    Here is a simple explanation. MySQL attempts to do the insert first. This is when the id gets auto incremented. Once increment, it stays. Then the duplicate is detected and the update happens. But the value gets missed.



    You should not depend on auto_increment having no gaps. If that is a requirement, the overhead on the updates and inserts is much larger. Essentially, you need to put a lock on the entire table, and renumber everything that needs to be renumbered, typically using a trigger. A better solution is to calculate incremental values on output.






    share|improve this answer













    This behavior is documented:




    If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
    would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL
    performs an UPDATE of the old row. For example, if column a is
    declared as UNIQUE and contains the value 1, the following two
    statements have similar effect:



     INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

    UPDATE table SET c=c+1 WHERE a=1;


    (The effects are not identical for
    an InnoDB table where a is an auto-increment column. With an
    auto-increment column, an INSERT statement increases the
    auto-increment value but UPDATE does not.)




    Here is a simple explanation. MySQL attempts to do the insert first. This is when the id gets auto incremented. Once increment, it stays. Then the duplicate is detected and the update happens. But the value gets missed.



    You should not depend on auto_increment having no gaps. If that is a requirement, the overhead on the updates and inserts is much larger. Essentially, you need to put a lock on the entire table, and renumber everything that needs to be renumbered, typically using a trigger. A better solution is to calculate incremental values on output.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered May 7 '14 at 11:58









    Gordon LinoffGordon Linoff

    794k37318421




    794k37318421







    • 1





      +1. Well said. Thanks for including the actual documentation. ;-)

      – ghoti
      May 7 '14 at 12:01











    • If auto_increment isn't a requirement do you think the gap is ok?

      – newbie
      May 7 '14 at 12:15






    • 12





      This is stupid issue with mysql. Ok, I don't relay on it to be without gaps, but today I got hit limit of 16000000+ row (MEDIUMINT) when I have only around 500000 records which got often updated. Problem is that I have another tables with goes beyond 250Gb of size linked to this one - and to update it to INT (and loose storage space when its totally unneeded) takes days.

      – lapkritinis
      Mar 27 '17 at 9:59







    • 3





      I don't understand the reasoning behind this design. While I don't mind the gaps, I see no reason for the autoincrementation to occur as the ID never existed, so it just creates a lot of garbage IDs for nothing.

      – jsmars
      Feb 26 '18 at 13:52






    • 1





      I'm updating multiple records regularly using ON DUPLICATE KEY UPDATE . I don't care for the gaps but I fear from hitting the max column value. will using ALTER TABLE table_name AUTO_INCREMENT=1 (which resets the auto_increment to the last rows id + 1) regularly after each batch update be a bad practice?

      – David Avikasis
      Oct 3 '18 at 21:48












    • 1





      +1. Well said. Thanks for including the actual documentation. ;-)

      – ghoti
      May 7 '14 at 12:01











    • If auto_increment isn't a requirement do you think the gap is ok?

      – newbie
      May 7 '14 at 12:15






    • 12





      This is stupid issue with mysql. Ok, I don't relay on it to be without gaps, but today I got hit limit of 16000000+ row (MEDIUMINT) when I have only around 500000 records which got often updated. Problem is that I have another tables with goes beyond 250Gb of size linked to this one - and to update it to INT (and loose storage space when its totally unneeded) takes days.

      – lapkritinis
      Mar 27 '17 at 9:59







    • 3





      I don't understand the reasoning behind this design. While I don't mind the gaps, I see no reason for the autoincrementation to occur as the ID never existed, so it just creates a lot of garbage IDs for nothing.

      – jsmars
      Feb 26 '18 at 13:52






    • 1





      I'm updating multiple records regularly using ON DUPLICATE KEY UPDATE . I don't care for the gaps but I fear from hitting the max column value. will using ALTER TABLE table_name AUTO_INCREMENT=1 (which resets the auto_increment to the last rows id + 1) regularly after each batch update be a bad practice?

      – David Avikasis
      Oct 3 '18 at 21:48







    1




    1





    +1. Well said. Thanks for including the actual documentation. ;-)

    – ghoti
    May 7 '14 at 12:01





    +1. Well said. Thanks for including the actual documentation. ;-)

    – ghoti
    May 7 '14 at 12:01













    If auto_increment isn't a requirement do you think the gap is ok?

    – newbie
    May 7 '14 at 12:15





    If auto_increment isn't a requirement do you think the gap is ok?

    – newbie
    May 7 '14 at 12:15




    12




    12





    This is stupid issue with mysql. Ok, I don't relay on it to be without gaps, but today I got hit limit of 16000000+ row (MEDIUMINT) when I have only around 500000 records which got often updated. Problem is that I have another tables with goes beyond 250Gb of size linked to this one - and to update it to INT (and loose storage space when its totally unneeded) takes days.

    – lapkritinis
    Mar 27 '17 at 9:59






    This is stupid issue with mysql. Ok, I don't relay on it to be without gaps, but today I got hit limit of 16000000+ row (MEDIUMINT) when I have only around 500000 records which got often updated. Problem is that I have another tables with goes beyond 250Gb of size linked to this one - and to update it to INT (and loose storage space when its totally unneeded) takes days.

    – lapkritinis
    Mar 27 '17 at 9:59





    3




    3





    I don't understand the reasoning behind this design. While I don't mind the gaps, I see no reason for the autoincrementation to occur as the ID never existed, so it just creates a lot of garbage IDs for nothing.

    – jsmars
    Feb 26 '18 at 13:52





    I don't understand the reasoning behind this design. While I don't mind the gaps, I see no reason for the autoincrementation to occur as the ID never existed, so it just creates a lot of garbage IDs for nothing.

    – jsmars
    Feb 26 '18 at 13:52




    1




    1





    I'm updating multiple records regularly using ON DUPLICATE KEY UPDATE . I don't care for the gaps but I fear from hitting the max column value. will using ALTER TABLE table_name AUTO_INCREMENT=1 (which resets the auto_increment to the last rows id + 1) regularly after each batch update be a bad practice?

    – David Avikasis
    Oct 3 '18 at 21:48





    I'm updating multiple records regularly using ON DUPLICATE KEY UPDATE . I don't care for the gaps but I fear from hitting the max column value. will using ALTER TABLE table_name AUTO_INCREMENT=1 (which resets the auto_increment to the last rows id + 1) regularly after each batch update be a bad practice?

    – David Avikasis
    Oct 3 '18 at 21:48













    1














    I had the same frustration and I have a solution.



    Let me first talk about "overheads". When I first wrote my DB update code, it did so many separate queries that it took 5 hours. Once I put on "ON DUPLICATE KEY UPDATE" I got it down to about 50 seconds. Amazing! Anyway the way I solved it means I have to do 2 queries, so instead of 1 minute I'm extending it to 2 minutes which I think is a fair cost considering.



    First I did a standard sql query with data that had updates and inserts, but I included "IGNORE" so this just bypasses the updates and only inserts the new stuff.
    "INSERT IGNORE INTO mytablename(stuff,stuff2) VALUES " -without the on duplicate key update. This means all the new records get put in. These new records wont break the auto_increment yet.



    Next I did the "ON DUPLICATE KEY UPDATE" version of that sql statement, now this breaks the auto_increment value, but all the updates and inserts we've put in are all perfect auto_incrememnt values. It's just the next new record we add will be wrong...



    So lastly you just patch up the mess by this sql:
    "ALTER TABLE mytablename AUTO_INCREMENT = " . ($TableCount + 1);



    remember to actually set $TableCount to the table count, then we add 1 and that's ready for when the next record gets written.



    This is cheap and dirty but I like it. Make sure you don't write to the database at the same time using another function etc, because it could give errors. I think there is a way to lock the table? But I don't need that in my case.






    share|improve this answer





























      1














      I had the same frustration and I have a solution.



      Let me first talk about "overheads". When I first wrote my DB update code, it did so many separate queries that it took 5 hours. Once I put on "ON DUPLICATE KEY UPDATE" I got it down to about 50 seconds. Amazing! Anyway the way I solved it means I have to do 2 queries, so instead of 1 minute I'm extending it to 2 minutes which I think is a fair cost considering.



      First I did a standard sql query with data that had updates and inserts, but I included "IGNORE" so this just bypasses the updates and only inserts the new stuff.
      "INSERT IGNORE INTO mytablename(stuff,stuff2) VALUES " -without the on duplicate key update. This means all the new records get put in. These new records wont break the auto_increment yet.



      Next I did the "ON DUPLICATE KEY UPDATE" version of that sql statement, now this breaks the auto_increment value, but all the updates and inserts we've put in are all perfect auto_incrememnt values. It's just the next new record we add will be wrong...



      So lastly you just patch up the mess by this sql:
      "ALTER TABLE mytablename AUTO_INCREMENT = " . ($TableCount + 1);



      remember to actually set $TableCount to the table count, then we add 1 and that's ready for when the next record gets written.



      This is cheap and dirty but I like it. Make sure you don't write to the database at the same time using another function etc, because it could give errors. I think there is a way to lock the table? But I don't need that in my case.






      share|improve this answer



























        1












        1








        1







        I had the same frustration and I have a solution.



        Let me first talk about "overheads". When I first wrote my DB update code, it did so many separate queries that it took 5 hours. Once I put on "ON DUPLICATE KEY UPDATE" I got it down to about 50 seconds. Amazing! Anyway the way I solved it means I have to do 2 queries, so instead of 1 minute I'm extending it to 2 minutes which I think is a fair cost considering.



        First I did a standard sql query with data that had updates and inserts, but I included "IGNORE" so this just bypasses the updates and only inserts the new stuff.
        "INSERT IGNORE INTO mytablename(stuff,stuff2) VALUES " -without the on duplicate key update. This means all the new records get put in. These new records wont break the auto_increment yet.



        Next I did the "ON DUPLICATE KEY UPDATE" version of that sql statement, now this breaks the auto_increment value, but all the updates and inserts we've put in are all perfect auto_incrememnt values. It's just the next new record we add will be wrong...



        So lastly you just patch up the mess by this sql:
        "ALTER TABLE mytablename AUTO_INCREMENT = " . ($TableCount + 1);



        remember to actually set $TableCount to the table count, then we add 1 and that's ready for when the next record gets written.



        This is cheap and dirty but I like it. Make sure you don't write to the database at the same time using another function etc, because it could give errors. I think there is a way to lock the table? But I don't need that in my case.






        share|improve this answer















        I had the same frustration and I have a solution.



        Let me first talk about "overheads". When I first wrote my DB update code, it did so many separate queries that it took 5 hours. Once I put on "ON DUPLICATE KEY UPDATE" I got it down to about 50 seconds. Amazing! Anyway the way I solved it means I have to do 2 queries, so instead of 1 minute I'm extending it to 2 minutes which I think is a fair cost considering.



        First I did a standard sql query with data that had updates and inserts, but I included "IGNORE" so this just bypasses the updates and only inserts the new stuff.
        "INSERT IGNORE INTO mytablename(stuff,stuff2) VALUES " -without the on duplicate key update. This means all the new records get put in. These new records wont break the auto_increment yet.



        Next I did the "ON DUPLICATE KEY UPDATE" version of that sql statement, now this breaks the auto_increment value, but all the updates and inserts we've put in are all perfect auto_incrememnt values. It's just the next new record we add will be wrong...



        So lastly you just patch up the mess by this sql:
        "ALTER TABLE mytablename AUTO_INCREMENT = " . ($TableCount + 1);



        remember to actually set $TableCount to the table count, then we add 1 and that's ready for when the next record gets written.



        This is cheap and dirty but I like it. Make sure you don't write to the database at the same time using another function etc, because it could give errors. I think there is a way to lock the table? But I don't need that in my case.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 3 '18 at 21:39

























        answered Dec 1 '18 at 22:57









        RosskiRosski

        112




        112





















            -1














            INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE material_item = data, ... hidden = data



            Yes remove the ID=ID as it will automaticly add where PRIMARY KEY = PRIMARY KEY...






            share|improve this answer


















            • 1





              but what if it has duplicate key it will increment right?

              – newbie
              May 7 '14 at 11:53











            • It will not if your table is MyISSAM, on InnoDB it will. There are other ways to fix the issue on InnoDB

              – Seti
              May 7 '14 at 11:58















            -1














            INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE material_item = data, ... hidden = data



            Yes remove the ID=ID as it will automaticly add where PRIMARY KEY = PRIMARY KEY...






            share|improve this answer


















            • 1





              but what if it has duplicate key it will increment right?

              – newbie
              May 7 '14 at 11:53











            • It will not if your table is MyISSAM, on InnoDB it will. There are other ways to fix the issue on InnoDB

              – Seti
              May 7 '14 at 11:58













            -1












            -1








            -1







            INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE material_item = data, ... hidden = data



            Yes remove the ID=ID as it will automaticly add where PRIMARY KEY = PRIMARY KEY...






            share|improve this answer













            INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE material_item = data, ... hidden = data



            Yes remove the ID=ID as it will automaticly add where PRIMARY KEY = PRIMARY KEY...







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 7 '14 at 11:50









            SetiSeti

            986820




            986820







            • 1





              but what if it has duplicate key it will increment right?

              – newbie
              May 7 '14 at 11:53











            • It will not if your table is MyISSAM, on InnoDB it will. There are other ways to fix the issue on InnoDB

              – Seti
              May 7 '14 at 11:58












            • 1





              but what if it has duplicate key it will increment right?

              – newbie
              May 7 '14 at 11:53











            • It will not if your table is MyISSAM, on InnoDB it will. There are other ways to fix the issue on InnoDB

              – Seti
              May 7 '14 at 11:58







            1




            1





            but what if it has duplicate key it will increment right?

            – newbie
            May 7 '14 at 11:53





            but what if it has duplicate key it will increment right?

            – newbie
            May 7 '14 at 11:53













            It will not if your table is MyISSAM, on InnoDB it will. There are other ways to fix the issue on InnoDB

            – Seti
            May 7 '14 at 11:58





            It will not if your table is MyISSAM, on InnoDB it will. There are other ways to fix the issue on InnoDB

            – Seti
            May 7 '14 at 11:58

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23516958%2fon-duplicate-key-auto-increment-issue-mysql%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현