1

I was trying trying to figure out if there is a way in SOQL to select/sort rows in a table with the longest Strings in a selected column.

Something similar to:

SELECT Id, Name FROM User ORDER BY LENGTH(Name)

The closest thing that I've found is the following:

SELECT Id, Name FROM User WHERE Name LIKE '__________________________'
2

With just SOQL? No. You can create a Name_Length__c formula though and ORDER BY that.

LEN(Name)

In execute anonymous, you can define an implementation of the Comparable Interface and sort that to get the longest value.

class LengthSorter implements Comparable
{
    final User record;
    final Integer length;
    public LengthSorter(User record)
    {
        this.record = record;
        if (String.isBlank(record.Name)) length = 0;
        else length = record.Name.length();
    }
    public Integer compareTo(Object instance)
    {
        LengthSorter that = (LengthSorter)instance;
        return this.length - that.length;
    }
}

List<LengthSorter> wrappers = new List<LengthSorter>();
for (User record : [SELECT Name FROM User])
    wrappers.add(new LengthSorter(record));
wrappers.sort();
| improve this answer | |
  • Thank you for you suggestion, but I'm afraid I cannot simply create a new field on Production objects... – wintermute Apr 19 '16 at 21:30
  • Please elaborate on your use case... you've given us next to nothing to work with. @winter – Adrian Larson Apr 19 '16 at 21:37
  • Actually, I already solved my problem with the last SOQL query in the topic, but I was curious if there could be additional ways of doing the same thing. – wintermute Apr 19 '16 at 21:48
  • @winter that only gives you records with a specific length, not necessarily the longest. – Adrian Larson Apr 19 '16 at 21:52
  • @winter If you're willing to use Apex you can do something like the above. – Adrian Larson Apr 19 '16 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.