Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save johncasimiro/734428 to your computer and use it in GitHub Desktop.
Save johncasimiro/734428 to your computer and use it in GitHub Desktop.
A code snippet that mimics the popular Select * SQL syntax in force.com's Apex language.
/*
* @description: A code snippet that mimics the popular Select * SQL syntax in force.com's Apex language.
*/
// Initialize setup variables
String objectName = 'Contact'; // modify as needed
String query = 'SELECT';
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
// Grab the fields from the describe method and append them to the queryString one by one.
for(String s : objectFields.keySet()) {
query += ' ' + s + ', ';
}
// Manually add related object's fields that are needed.
query += 'Account.Name,'; // modify as needed
// Strip off the last comma if it exists.
if (query.subString(query.Length()-1,query.Length()) == ','){
query = query.subString(0,query.Length()-1);
}
// Add FROM statement
query += ' FROM ' + objectName;
// Add on a WHERE/ORDER/LIMIT statement as needed
query += ' WHERE firstName = \'test\''; // modify as needed
try {
List<Contact> contacts = database.query(query);
} catch (QueryException e){
//perform exception handling
}
@edgartheunready
Copy link

thanks

@harmon
Copy link

harmon commented Mar 7, 2014

Awesome!

@abentkamp
Copy link

Thanks, that saved me a lot of work.

One little problem I had: In case you are not adding related object's fields, line 12 should be
query += ' ' + s + ',';
without the space after the comma to make sure the comma is really the last character when it gets stripped off.

@arufian
Copy link

arufian commented Oct 14, 2014

Clever!

@jduelfer
Copy link

jduelfer commented May 18, 2016

Awesome! thanks. And yeah I made the same modification @benti

@psmak4
Copy link

psmak4 commented Jan 3, 2018

Where do you get that Schema object?

@pranayjswl007
Copy link

Thanks Much appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment