An attempt at Bacon numbers in SQL by Adomas Boruta. I instead of writing recursive selection for Bacon number, I wrote a procedure which calculates the distance from some person to all others (-1 being unrelated, 0 is the person itself and positive number is the distance). For small database, it took 12m 27s 332ms to complete. It requires table: CREATE TABLE PEOPLE_DISTANCE ( id INTEGER IDENTITY PRIMARY KEY, person_id INT NOT NULL, related_person_id INT NOT NULL, distance INT NOT NULL ); Procedure: CREATE PROCEDURE generate_distance_to_person(IN p_id INT) MODIFIES SQL DATA BEGIN ATOMIC DECLARE count_var INTEGER; DECLARE n INTEGER; BEGIN ATOMIC DELETE FROM PEOPLE_DISTANCE WHERE person_id = p_id; INSERT INTO PEOPLE_DISTANCE (person_id, related_person_id, distance) SELECT p_id AS person_id, id AS related_person_id, -1 AS distance FROM PEOPLE; UPDATE PEOPLE_DISTANCE SET distance = 0 WHERE person_id = p_id AND related_person_id = p_id; SET count_var = 1; SET n = 0; WHILE count_var > 0 DO UPDATE PEOPLE_DISTANCE SET distance = n + 1 WHERE person_id = p_id AND related_person_id IN ( SELECT c2.PERSON_ID AS person_id FROM PEOPLE_DISTANCE INNER JOIN CREDITS c1 ON PEOPLE_DISTANCE.related_person_id = c1.PERSON_ID INNER JOIN CREDITS c2 ON c1.MOVIE_ID = c2.MOVIE_ID INNER JOIN PEOPLE_DISTANCE pd ON pd.related_person_id = c2.PERSON_ID WHERE c1.PERSON_ID <> c2.PERSON_ID AND c1.TYPE = 'actor' AND c2.TYPE = 'actor' AND pd.distance = -1 AND pd.person_id = p_id AND PEOPLE_DISTANCE.person_id = p_id AND PEOPLE_DISTANCE.distance = n ); SET count_var = DIAGNOSTICS(ROW_COUNT); SET n = n + 1; END WHILE; END; END; And calculation for a person can be performed like this: CALL GENERATE_DISTANCE_TO_PERSON(107303); Results can be extracted like this: SELECT person_id, distance, count(*) AS total FROM PEOPLE_DISTANCE GROUP BY person_id, distance ORDER BY distance