Improved sorting and errors on duplicate constraints (+ tests)