Is there a way to do custom soql order by instead of ASC or DESC?

528    Asked by dipesh_9001 in Salesforce , Asked on May 22, 2023

Is there a way to do custom order by instead of ASC or DESC?

There is a picklist field -> Color__c on a custom object - Products__c - which has following values:

  1. RED

  2. YELLOW

  3. BROWN

If i write a SOQL: Select id, LastOrderDate__c,Color__c from Products__c where Name = 'Shoes' ORDER BY Color__c DESC

its returning YELLOW,RED,BROWN records in this order but i want a custom order by which i prioritise RED over YELLOW, is there way to do a custom order by instead of ASC or DESC?

Answered by Elizabeth Jordan

No, you cannot do the custom soql order by instead of ASC or DESCĀ You can, if you wish, create a new formula field on your object that maps colours to their desired ordering keys, using something like a CASE() formula. You can then order by that formula field. Note of course that that may come with performance implications, and you'll have to be aware of the formula character limit depending on how many values you have.



Your Answer

Interviews

Parent Categories