DELIMITER $$ CREATE FUNCTION `getParent`(n INT) RETURNS VARCHAR(255) BEGIN DECLARE parent VARCHAR(2555); SELECT parent_id INTO parent FROM your_table WHERE id = n; IF parent IS NOT NULL THEN RETURN CONCAT(parent, ',', getParent(parent)); ELSE RETURN ''; END IF; END$$ DELIMITER ;