Sort:  

Yes, to be honest, I'm not sure how to fetch the data with a SQL query. It might need recursive queries. Hivemind also uses multiple queries and processing at Python side to solve the problem.