Hot answers tagged

154

I know only one: Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM Contact]); Here is the doc: Maps of sObjects


83

No, but you can query like this which does the same thing as what you're trying to do: String[] filters = new String[]{'acme%','ib%'}; List<Accounts> accs = [select id, name from Account where name like :filters];


80

Believe it or not bind variables actually work in dynamic SOQL: Map<Id,Account> accts = new Map<Id,Account>([select Id from Account]); Set<Id> accountIds = accts.keySet(); String q = 'select id from Contact where AccountId in :accountIds'; List<Contact> cts = Database.query(q); Note that you can't embed method calls (e.g. AccountId ...


60

Let's make a quick comparison of the two: Definition SOQL (Salesforce Object Query Language) Use the Salesforce Object Query Language (SOQL) to construct simple but powerful query strings in the queryString parameter in the query() call, in Apex statements, in Visualforce controllers and getter methods, or in the Schema Explorer of the Force.com ...


55

Alternatively, if you have a list already -- say you're in a situation where you need a map, but aren't in a mood to refactor your entire class to handle a map, you can convert your list of results to a map thusly: Map<Id,OBJ_TYPE> mapFromList = new Map<Id,OBJ_TYPE>(List_object_variable); This will generate a map from the list as if you'd ...


53

You can use toLabel() to convert the picklist api name to a label: SELECT toLabel(CUSTOM_PICK_LIST_COL__C) FROM OPPORTUNITY


45

If it's not in Apex code you don't need the : and you need to add ( ) So your SOQL could be rewritten as: SELECT Id, Syndication_Documents__c FROM ContentVersion WHERE Syndication_Documents__c IN ('a4fa0000000KzbV','a4fa0000000KzbW') If you're doing it from Apex and have a Collection (Set, List, or Map) you can bind them to the query and avoid the ...


43

SOQL has very limited aliasing support. You can alias the table, e.g. SELECT a.name FROM Account a, but that's of very little use. In most contexts you cannot alias fields. The one exception is for queries that use aggregations, like SELECT COUNT(Id) recordCount FROM Account allows you to alias the result of the aggregation from it's default expr0 to ...


42

Let's take the following SOQL: List<Account> dd = [ SELECT id, (SELECT Name FROM Contacts), // <- first subquery (SELECT AccountID FROM Cases) // <- second subquery FROM Account WHERE id IN (SELECT AccountID FROM Case) // <- not counted ]; In the above query there are total 3 ...


37

The exception is thrown because you are assigning the results of your query directly to an account, rather than a list of accounts. When you assign the results of a query directly to an instance of a variable Salesforce will throw an exception if the query returns zero rows. As you are using an instance of an account rather than a list you cannot use the ...


32

Just use addDays with a negative value: Date.today().addDays(-1)


31

QueryMore is the appropriate means of accomplishing this if you're getting data all at once. For pagination, such as in a website or portal, sort by some value then use filters. I would recommend a field with a high cardinality (e.g. many unique values) because it makes pagination that much easier. I've posted this answer elsewhere, but I'll post it here, ...


31

In Apex Code, the SOQL engine automatically includes RecordTypeId and Id in any query result, even if you don't ask for it. There are a few other hidden parameters that appear in a query when presented to the SOQL engine. For example, if you don't include a LIMIT statement, or set it to higher than 1+Limits.getLimitQueryRows()-Limits.getQueryRows(), the ...


30

There is no way to Select * with SOQL. You can however work-around this limitation by using dynamic SOQL and describe methods to get all of the fields on the object. This is described in detail in this post by Cory Cowgill: Building Dynamic SOQL - Select All Query


29

Just found out today that with the Spring 19' update there is a new setting in the "Setup -> Permission Sets -> (choose an existing or create a new one) -> App Permission -> Content -> Query All Files: Allows View All Data users to SOQL query all files in the org". This is not enabled by default for the admin user but you can at least enable it in a Profile/...


29

You could use your current query and get the size attribute of the list after the query finishes: List<User> users = [SELECT Name, (SELECT id FROM Applications__r) FROM User]; for (User u : users) { // do something with it... u.Applications__r.size(); } Alternatively, you can use an AggregateResult query which would query the child and group ...


29

(tl;dr at bottom) Filter Speed If you can use Map.keySet(), you'll get a Set back in about 1/10th of the time versus a loop over those same records and adding all the values. Of course, the Map<Id, SObject>(List<SObject>) constructor only works on Id, not on related ID values, which means you'd have to fall back to a loop. However, in cases ...


28

Q1: I am bit confused about what will happen ? Will it fail(throw exception) or will it wait for 4-5 seconds and then if it doesn't get access it will throw an exception? You will get somewhere around 5 seconds before it will exclusively fail. The user will be advised to try their save again. The status code will be "UNABLE_TO_LOCK_ROW". Q2 : In the ...


28

Take a look at the UserLicense object documentation. There is a field called LicenseDefinitionKey that uniquely identifies a particular user license and the documentation lists all possible values. From the documentation: A string that uniquely identifies a particular user license. Label is License Def. ID. Values are: And one of the values: SFDC: ...


28

The documentation states: Distance is calculated as a straight line—as the crow flies—regardless of geography and topography between the two points. In reality Salesforce uses the haversine formula to calculate the great-circle distance between two points. For any two points on a sphere, the haversine of the central angle between them is given by ...


26

You can not use text area fields in SOQL and SOSL filter criterias. Try this approach: List<Project__c> projects = new List<Project__c>(); for(Project__c proj : [SELECT Name, Status__c, Description__c FROM Project__c WHERE Name LIKE '%' + String.escapeSingleQuotes(name) +'%' + OR Status__c = String.escapeSingleQuotes(status)]) { if(proj....


25

(comical but unsupported) You can wedge your aggregate query inside of a FOR loop. This expands the ceiling beyond the 50,000 limit. Ultimately undocumented behavior, that probably shouldn't be relied upon. Integer total = 0; for (AggregateResult result : [ SELECT COUNT(Id) FROM SomeObject__c ]) total += (Integer)result.get('expr0'); System....


24

This is possible through Apex, but not SOQL --- and no Metadata API required. To determine whether a given SObject's RecordType is available to a given user's profile, you will need to use the Apex DescribeSObjectResult getRecordTypeInfos() call on that SObject (see the docs here). This returns a list of RecordTypeInfo objects corresponding to all ...


24

CreatedDate is a datetime field so I guess you would need to specify the time component. Can you do something like where you just append the time portion to be 12 am by default. WHERE CreatedDate > 2005-10-08T00:00:00Z Or you can use Date Literals like WHERE CreatedDate > YESTERDAY For more on date formats and more literal values see, http:/...


24

I think you are limited to the size of the query not exceeding 20,000 characters. https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_soslsoql.htm SOQL statements can't exceed 20,000 characters. For SOQL statements that exceed this maximum length, the API ...


23

Wow, that's an interesting one! I doubt it's allowed though (at least without having to use Dynamic SOQL). You can always do this instead: Date d = System.today() - 7; List<Opportunity> opportunities = [SELECT OwnerId, Amount, Probability FROM OPPORTUNITY where Amount > 0 and LastModifiedDate < :d];


23

To filter a SOQL query on a datetime field with a day value, use the DAY_ONLY SOQL operator. SELECT Id FROM Account WHERE DAY_ONLY(CreatedDate) > 2005-10-08 You can bind a date variable into the SOQL Query as well, but the results might not be what you expect as there the date variable would be cast into a DateTime type at run time.


23

What happens if you alias the field, does that work? AggregateResult[] groupedResults = [ SELECT Account.Type type, count(Id) oppCount FROM Opportunity GROUP BY Account.Type]; // snip System.Debug(ar.Get('type')); Notice that if you are doing an aggregation (GROUP BY) you can create an alias for both the summarized field and for other fields. ...


23

CreatedDate is of DateTime type so your query must use the format from the very top of the article you've linked to: YYYY-MM-DDThh:mm:ssZ (optionally with timezones) SELECT Id FROM Case WHERE CreatedDate >= 2013-12-21T00:00:00Z AND CreatedDate <= 2013-12-23T23:59:59Z Another example: SELECT Id FROM Account WHERE CreatedDate > 2005-10-08T01:02:...


23

Somehow I found the solution : String[] nameFilters = new String[]{'%Sale%', '%Opportunity%', '%Catalog%'}; List<Pricebook2> myList = [select Name from Pricebook2 where name LIKE :nameFilters ]; for (Pricebook2 rec : myList) { rec.Is_Auto_Maintained__c = true; rec.Price_Type__c ='Net'; } update myList;


Only top voted, non community-wiki answers of a minimum length are eligible