Skip to content

Instantly share code, notes, and snippets.

@westc
Last active June 10, 2025 16:34
Show Gist options
  • Save westc/de88d310150cdf313cc62ab651980247 to your computer and use it in GitHub Desktop.
Save westc/de88d310150cdf313cc62ab651980247 to your computer and use it in GitHub Desktop.
getFieldNames() and queryAllFields() Apex functions that can be used to query all of the fields of an sobject.
public static String[] getFieldNames(String sobjectName) {
String[] fieldNames = new String[]{};
Schema.SObjectType sobjectType = Schema.getGlobalDescribe().get(sobjectName);
if (sobjectType != null) {
Map<String, Schema.SObjectField> fieldsMap = sobjectType.getDescribe().fields.getMap();
fieldNames.addAll(fieldsMap.keySet());
}
return fieldNames;
}
public static SObject[] queryAllFields(String sobjectName) {
return queryAllFields(sobjectName, new Map<String,Object>());
}
public static SObject[] queryAllFields(String sobjectName, Map<String,Object> options) {
// Get the field names
String[] fieldNames = getFieldNames(sobjectName);
// Construct the SOQL query
String query = 'SELECT ' + String.join(fieldNames, ',') + ' FROM ' + sobjectName;
if (options.containsKey('where')) {
query += ' WHERE ' + (String)options.get('where');
}
if (options.containsKey('orderBy')) {
query += ' ORDER BY ' + (String)options.get('orderBy');
}
if (options.containsKey('limit')) {
query += ' LIMIT ' + (Integer)options.get('limit');
}
if (options.containsKey('offset')) {
query += ' OFFSET ' + (Integer)options.get('offset');
}
// Execute the query and return the results
return Database.queryWithBinds(
query,
options.containsKey('bindMap') ? (Map<String,Object>)options.get('bindMap') : new Map<String,Object>(),
options.get('isInSystemMode') == true ? AccessLevel.SYSTEM_MODE : AccessLevel.USER_MODE
);
}
System.debug(JSON.serializePretty(
queryAllFields(
'Shipment__c',
new Map<String,Object>{
'where' => 'Id = :id',
'bindMap' => new Map<String,Object>{'id' => 'a1D5f000003LyHKEA0'}
}
)
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment