database trickery and sorting stuff