I am trying to provide the value for auto increment value through the subquery in mysql
I tried with this command
alter table xxx auto_increment = (select max(id) from xxx) ;
But am getting the syntax error as
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘(select max(id) from xxx)’ at line 1
Please anyone help me on this issue….Thanks in advance
2
Answers
You cannot set AUTO_INCREMENT by this way – new AUTO_INCREMENT value is literal and cannot be an expression.
To achieve your goal it is enough to set AUTO_INCREMENT to 1. For this statement the provided value is always checked, and if some rows exists and it must be above provided value then it is adjusted to
MAX(AI_column) + 1
automatically.DEMO:
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
fiddle
You need to use dynamic sql for this:
fiddle