Sort by rid to maintain consistent ordering