Query sortening by Python only