Search code examples
mysqlbatch-insert

How to auto-increment ID in Batch insert


I have the following query that I want to execute

INSERT INTO TableB (ID, Age, RollNo)
SELECT (select (max(id) + 1) from TableB), Age, RollNo
FROM TableA
WHERE Age > 20 AND RollNo < 500

Now all the new entries have the same ID in the TableB

Am i doing something wrong.

P.S. I cannot change the column properties, I cannot set it to AUTO-INCREMENT, it needs to have default value NULL


Solution

  • Declare the ID column in TableB as AUTO_INCREMENT which will eventually serve this purpose

    ALTER TABLE TableB MODIFY COLUMN ID INT auto_increment
    

    In that case you can generate those numbers like

    SET @id := (SELECT MAX(ID) FROM TableB);
    
    INSERT INTO TableB (ID, Age, RollNo)
    SELECT (@id := @id + 1), Age, RollNo
    FROM TableA
    WHERE Age > 20 AND RollNo < 500;