Is there a way to create a custom ORDER BY in SOQL using Apex

apexsoql

Is it possible to make a custom ORDER BY?

SELECT Badge_Name__c, Session_Position__c FROM Attendee__c WHERE Event__c =: eventId ORDER BY Session_Position__c (???)

Session_Position__c is a picklist.

I'd like to display the return of that query like this in my visualforce page:

  1. Moderator
  2. Keynote Speaker
  3. Special Guest
  4. Co-chair
  5. [A-Z] Badge Name

First Moderators, secondly Keynote Speakers, thirdly Special Guests and so on… so ASC or DESC doesn't fit in this scenario (only for the Badge Name, using ASC).

Any apex programming logic suggestions?

Best Answer

You could implement the comparable interface. While that wouldn't allow you to do the ordering in the query, it would allow you to use the sort() method that the List class provides.

Honestly though, this one is probably achieved easier by creating a simple formula field. The formula field would assign integer values to each value of your picklist, and you would assign integer values in a way that then allows you to use it in ORDER BY (either DESC or ASC).

Re-ordering the picklist values to be in your preferred order would probably be the simplest of all (picklist sort order in SOQL is determined by the order of picklist values as shown when you view the field in setup/the object manager), but that may not be an option for everyone and is susceptible to inadvertent meddling.

Related Topic