Refactored SQL code for tree building