Sort on database level instead of in memory