3

I know how I can sort by id or number like

$getTicket = $sql->query("SELECT * FROM `ticket` 
                          WHERE `user`='$user->name' 
                          ORDER BY `id` DESC");

I have Status in the ticket table, and in that I have 3 things:

  1. Answered
  2. Unanswered
  3. Done

I want to sort it in this way:

  1. Unanswered
  2. Answered
  3. Done

Is there a way to do this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Patric Nøis
  • 208
  • 2
  • 8
  • 27
  • dupe of [Ordering by specific field value first](https://stackoverflow.com/questions/14104055/ordering-by-specific-field-value-first) – underscore_d Jul 07 '20 at 15:35

2 Answers2

6

Do simple as-

ORDER BY FIELD(Status, 'Unanswered', 'Answered', 'Done')
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Rohit Kumar
  • 1,948
  • 1
  • 11
  • 16
4

You can generally use case

SELECT * FROM `ticket` 
WHERE `user` = '$user->name' 
ORDER BY case when Status = 'Unanswered' then 1
              when Status = 'Answered' then 2
              else 3
         end

or MySQL specific find_in_set

SELECT * FROM `ticket` 
WHERE `user` = '$user->name' 
ORDER BY find_in_set(Status, 'Unanswered,Answered,Done')
juergen d
  • 201,996
  • 37
  • 293
  • 362