def sorted(field_name, ascending=True, fields=None, count=5):
    if field_name is None:
      raise Exception('Sort field must be specified')
    direction = '' if ascending else ' DESC'
    projection = Sampling._create_projection(fields)
    return lambda sql: 'SELECT %s FROM (%s) ORDER BY %s%s LIMIT %d' % (projection, sql, field_name,
                                                                       direction, count)