Functional sorting

Too many queries. Find way to lessen them.