SOQL “Select *”

badideaSo, let me start off this post by saying how this is a bad idea for nearly all applications.  Wildcarding columns has performance impacts and kittens die when you do it.  There is a reason Salesforce doesn’t allow you to do this natively.

THAT SAID, I did happen to come across a scenario where I needed to export multiple records to an Excel file, and there were fields being added, removed, and changed on a quarterly basis.  Fieldset?  Sure, I could go that way, but I figure I try something new – a “set it and forget it” option.

So, I decided I needed to create a “Select *” option that:

  • Dynamically returned all fields in an sObject
  • Could reference and return any object
  • Could either reference a set of Ids or just pull the top 50 records
  • Can handle fields I do NOT want to return
  • Handle multi-level sorting of results

So after a little baby punching and kitten killing, I created a monster.  =)

You can check out my GitHub repo here, but this is the high-level explanation of what beast I just unleashed.

// Specify Record Ids
Set<Id> setRecordIds = new Set<Id>();
setRecords.add(whatever);

// Exclude Audit Fields
Set<String> setBlockedFields = UtilityMethods.setAuditFields;
setBlockedFields.add('whatever__c');

// Set Sorts
Map<String, String> mapSort = new Map<String, String>();
mapSort.put('State', UtilityMethods.G_SORT_ASCENDING);
mapSort.put('Name', UtilityMethods.G_SORT_ASCENDING);
// Awaken the monster
Map<Id, SObject> mapRecordData = UtilityMethods.objRecordData('Account', setRecordIds, setBlockedFields, mapSort);

// Do stuff with the results
GatesOfHell.spawnSatanEternal(mapRecordData);

young-frankenstein-song-and-dance-menSo – please don’t abuse this.  I release this monster into the world as more of an academic exercise as well as ya know what – you may have a real need for this at some point.

Do NOT, by any means, use this in your day-to-day Apex coding.  It’s bad and if you use this, you should feel bad.

Now…if you flipped the purpose of this code to be an INCLUSIVE field set instead of an EXCLUSIVE field set, then I’ll give you a pat on the back.  =)

Advertisements