Fix issues with recursive SQL queries