ALTER TABLE `vn`.`starredModule` ADD `position` INT NOT NULL AFTER `moduleFk`; SET @count:=0; UPDATE `vn`.`starredModule` sm JOIN ( SELECT sm.id, IF(@workerFk = sm.workerFk, @count:=@count+1, @count:=1) AS position, @workerFk:=sm.workerFk FROM `vn`.`starredModule` sm ORDER BY workerFk, moduleFk ASC) AS smt ON smt.id = sm.id SET sm.position = smt.position;