Fix sorting in large database