How get current AUTO_INCREMENT value for any table Ask


(Darii Dumitru) #1

Hi,

how do I get the current AUTO_INCREMENT value for a table in MySQL


(Andrew) #2

Do you mean this?

select max(id) from table;


(Hendri Winarto) #3

Hi, I think using max + 1 will risk breaking the auto_increment value if the last record with max ID was previously deleted. Instead, we can get the next value for next auto_increment using this syntax :
$expression = new \yii\db\Expression("
AUTO_INCREMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ‘table_name’
");
$next_id = (new \yii\db\Query)->select($expression)->scalar();