Questions tagged [dynamic-soql]

Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code.

Filter by
Sorted by
Tagged with
71
votes
4answers
23k views

Elegant way to convert Set<Id> into String for Dynamic SOQL IN comparison

When I have a Set of Id's and I want to do a dynamic SOQL query that I want to use it in for an IN comparison, I have to convert the Set to string in the format of: ('id1','id2',id3',...) The way I ...
34
votes
5answers
32k views

Howto wildcard SELECT * to query all fields of objects in APEX?

I have created sObject and I need all the fields and I have many. Is there a way I can directly get all of them rather then typing each one of them.
30
votes
3answers
33k views

Use Set<Id> in dynamic SOQL IN-clause in method without Database.query()

I know and love that Apex is automatically converting Set to a valid SOQL string when it is used referenced like Set<Id> ids = ... String soql = 'SELECT ... WHERE Id IN :ids'; and passed to a ...
27
votes
1answer
9k views

Getting “__r” relationship name from Schema.SObjectType.Fields

Say I have a master-detail relationship between two objects, Schematic__c and Part__c. I can SOQL query the master from the detail: [SELECT Schematic__r.Name FROM Part__c] If I'm building a query ...
26
votes
2answers
5k views

Bind variable with dotted name not working in dynamic SOQL

As mentioned in this answer, it's possible to use bind variables in dynamic SOQL queries. This seems like a great way to avoid SOQL-injection, and to build a query string once but use it multiple ...
22
votes
1answer
532 views

SOQL bind variable scope behavior

After I posted this question, I found a similar post that seemed to answer it: Variable scope - database.query() has access to variables not in scope. I'll leave this in place for now, as I am not ...
15
votes
4answers
2k views

How to find out if an Object is a collection or single value?

I have some dynamic SOQL code in which I'd like to identify whether a method argument is a collection or a single value: SObject[] query(SObjectType sobType, String field, Object data) { // Want ...
13
votes
5answers
4k views

SOQL query to return records with numeric values

I'm trying to write a dynamic SOQL query to get an object's record that has numeric value in a particular field. I'm trying to do something similar like below: Account acc; queryString = 'SELECT Id,...
12
votes
3answers
23k views

Filtering by Long Text Area field in SOQL

I'm working on a custom search page, which will search through the fields of the Project object. I use dynamic SOQL query similar to that: String query = 'SELECT Name, Status__c ... FROM ...
12
votes
1answer
15k views

SObject row was retrieved via SOQL without querying the requested field:

I am getting this error with the code below. I've looked into the other cases on here. In my case I am referring to a relationship name (__r) which I am assuming is pulling correctly. It's a field ...
11
votes
4answers
11k views

Can a SOQL query selecting all columns be generated at runtime?

It seems like SOQL does not have an equivalent to SQL's "SELECT * FROM ..." (If SOQL has this syntax, show me and I will mark that as the answer.) To get around this limitation, I have been using a ...
10
votes
2answers
8k views

What makes a field not groupable

I'm trying to use an aggregate query, but one of the fields I want to group by is not groupable (saw it in the soql error and then verified groupable=false in the metadata). It's just a number field ...
10
votes
3answers
21k views

How to use Count() in SOQL

I have a custom object. This custom object has a field Cabin_Type__c, which has values of Twin and Luxury. There is another field Deck_Type__c which is just the number of the deck such as 1,2,3,etc. ...
10
votes
1answer
6k views

How to use dynamic SOQL to instantiate a MAP

I've tried doing it, but I get this error: Compile error at line 101 column 32 Invalid initial type List<SObject> for Map<Id,Opportunity> Here's my code: //build out the set set <id&...
10
votes
2answers
2k views

Accessing child records returned from SOQL via generic SObject

I'm currently querying the records of a custom object, including some related child records. Unfortunately the parent object is unknown, so the returned results from the query is a list of SObjects. ...
10
votes
2answers
5k views

How do you dynamically select fields in for loop query?

Something has been bugging me for a little while now, and I can't seem to find the answer anywhere... When working with large queries, it is a good idea to use a for loop to iterate through the query ...
10
votes
1answer
520 views

Does the `getSObjects` method on `SObject` work with Person Account child relationships?

Our app uses a lot of dynamic SOQL, and in a client org I'm currently getting an error which I can't explain when we're performing a large query against account, including subqueries for all related ...
9
votes
5answers
2k views

What's wrong with this SOQL

Declared a string and assigned SOQL value as shown below. While running I am getting an error. String country = 'United States'; String accountQuery = 'SELECT Id,BillingPostalCode,County_Name__c '+ ...
9
votes
1answer
3k views

Get the sObjectType of a field dynamically

I have a field Board_Name__c that is a lookup from Opportunity back to Opportunity. How can I dynamically find out that Opportunity.Board_Name__c references the Opportunity sObject while Opportunity....
9
votes
1answer
17k views

How to use the escapeSingleQuotes method?

I'm trying to use this method in a dynamic SOQL query. Follow the sample code: public static String getRowById(String sobjName, id id) { String query = 'SELECT '; Map<String, ...
9
votes
0answers
84 views

Is there a work around to allow binding of variables in the sfdx force:data:tree:export query file

When using sfdx force:data:tree export with an in-line query, you can bind variables by creating them in the cli before running the export command, like so: CURRENTYR=2017 sfdx force:data:tree:export ...
8
votes
4answers
880 views

Genuine SOQL Injection issue or False Positive?

Trying to work out if this a valid issue with my code, or just a false positive I can note in report for Security Review. I have provided a slightly simplified version below. The Id I am querying for ...
8
votes
2answers
2k views

Apex CPU Time limit in Batch start() - is this a Query Timeout and how to cope with?

I have a Batch iterating over a large amount of records (with many fields) and 2 of their related child records. The start() method uses Dynamic SOQL to fetch them via QueryLocator to vary which ...
8
votes
3answers
2k views

Querying Randomly

I am looking to implement a raffle against the user table, where one is picked at a random amongst a pool of 100k+ users. How would you perform the random query without a batch job or modifying the ...
8
votes
2answers
20k views

How to execute a dynamic SOQL query with a variable number of “in” terms?

I understand from answers like this Bind variable with dotted name not working in dynamic SOQL that binding Apex variables into dynamic SOQL is more limited than into static SOQL. I want to write ...
8
votes
1answer
2k views

Field Sets & Dynamic DML & Describing Fields Included in Field Set

I am attempting to write generic code which will use a fieldset, allowing for dynamic creation of a query. This bit is documented well enough in dynamic DML examples from SFDC. In addition to the ...
8
votes
1answer
2k views

CurrencyIsoCode - Auto included in query results, except for test cases

I've implemented some functionality around MultiCurrency in a Managed package. Since it needs to be able to support non-multi-currency orgs, all references to the CurrencyIsoCode field are done using ...
7
votes
4answers
5k views

How do I SOSL across objects, matching all records with FIND clause?

To all the expert SOSL gurus lurking out there, I thought this will be an interesting one: I have some SObjects of different types and I want to return their Name values in a single query. In ...
7
votes
1answer
3k views

How to implement a generic DAO object for Service pattern with Apex?

Considering advice given for DAO objects or Service pattern from What is a good set of coding conventions for Salesforce development?, I'm wondering how can they be made generic enough? Some generic ...
7
votes
1answer
2k views

QueryException: Non-selective query (it is selective)

I am trying to query a Custom Object called Lead_Assignment__c based on some criteria. Original query below: List<Lead_Assignment__c> leadAssignments = [ SELECT Segment__c, Queue_Name__c, ...
7
votes
5answers
1k views

Trying to LIMIT a SOQL Statement based upon projected Heap size

THE GOAL: Return as many rows as possible from a Remote method without hitting Heap limits. We have a Visualforce page calling into a @RemoteAction method in Apex to return sObjects to the page. The ...
7
votes
3answers
2k views

Unable to perform a COUNT() query on object with many million records

I have a custom object with around 25.000.000 records and need to perform a single count query to find those records where a field has a certain value. I could get none of the following queries to ...
7
votes
1answer
2k views

Force Dynamic Soql results to include fields with null value

So I've read a lot about this and it seems that queries run with Database.query(queryString) will skip over any field values set to null instead of returning the property set to null This has cause a ...
7
votes
2answers
1k views

BillingAddress in query generate error

I have a query like below in an Apex Class in Sandbox. query = 'SELECT Id, Name, BillingAddress, BillingLatitude, BillingLongitude FROM Account WHERE Name = \''+ name +'\' AND '; query += '...
7
votes
2answers
5k views

trying to get a count of records(records more than 50000 in object) in one object through apex class

Trying to get a count of records(records more than 50000 in object) in one object through apex class(Getting limit Exception). Looking for any alternate solution. I used database.countQuery()...
6
votes
3answers
2k views

Possible to use bind :variable inside SELECT clause?

I cannot use the String[] ss inside the SELECT statement. It is giving me errors: unexpected token: ':' Code public void getSubscribers(Id listId){ String[] ss = new String[]{'Id', 'Name'}; ...
6
votes
2answers
25k views

use string array in IN clause in dynamic soql

I have an array of strings i'd like to use in the IN clause of a dynamic soql query. if i wasn't building the string at runtime i could simply use (from the SF docs): String[] ss = new String[]{'a', ...
6
votes
3answers
344 views

Select into Map using Database.query()

So we all know it is possible to directly select into a Map, like this: Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id, Name FROM Account]); Is it possible to do the same ...
6
votes
3answers
1k views

Why I can not use Map in dynamic query

Map<Id, Account> maps = new Map<Id, Account>(); for(Account acc : [Select Id from Account]) { maps.put(acc.Id, acc); } String s = 'Select Id from Account Where Id IN : maps.keySet()'...
6
votes
1answer
826 views

Undelete error: entity is deleted

I'm trying to undelete records using apex and it is throwing me an error: entity is deleted List<MyObject__c> undeleteObj = [select id, Unique_Id__c from MyObject__c where ...
6
votes
2answers
531 views

Check if a .txt file of IDs all exist in Salesforce

I receive a .txt files of type ID, e.g. 003U000000PL9LN, 001U000000PL9LM, a1fU000000PL9LO. I need to check if these IDs correspond to valid objects within Salesforce. I have a List of IDs in Apex. ...
6
votes
1answer
6k views

How to Search a text in all fields in all objects and return all values?

Can I find a string from all fields from all custom and standard objects and return the data (all field data) of all the records that matches for all the fields of those objects?? Also is there an ...
6
votes
2answers
3k views

Dynamic SOQL Queries and Managed Namespaces

If I create a dynamic SOQL query (via strings, to be used with Database.query) in an unmanaged code environment, and then the code is converted to a managed environment, are namespace considerations ...
6
votes
2answers
2k views

How to take a field value after dynamic SOQL

I am trying to get field value from a dynamic SOQL result. Here i have a object where end user need to enter the field name which he need. I am SOQL it like this: UserprofileSOQL = '...
6
votes
1answer
2k views

Integration - Outbound Messages - configure Endpoint URL dynamically!

Hello guys! Scenario: I am sure all of you come across this everyday if you do integrations. I have 2 sets of machines (Training and Production). The outbound messages in prod. instance point towards ...
5
votes
2answers
6k views

isDeleted=True is not working in SOQL query

Wondering why this query will retrieve ZERO records when executed in Workbench and Developer console. (Though i have records in Recycle Bin) Select Id, IsDeleted FROM Account WHERE IsDeleted = TRUE ...
5
votes
2answers
5k views

Concatenate fields in SOQL queries in the WHERE clause (no Apex)

I am trying to run SOQL statement in salesforce.schema tool of FORCE.COM the following query: Select c.LastName, c.FirstName From Contact c WHERE (FirstName+' '+LastName) In ('Good Name','Bad Name') ...
5
votes
3answers
6k views

Dynamic SOQL How to bind date?

soql = 'select A__c,EmplId__c, B__c,Date__c from Transaction__c Where Transaction__c.name!=null'; if (!branch.equals('')) system.debug('test br1'); soql += ' and A__c LIKE \''+String....
5
votes
1answer
2k views

Query for a list of IDs using Dynamic SOQL from JavaScript

I'm trying to update multiple records and then send email notification using custom list button. For this I need to get few fields off the related list. One option would be traverse thru the related ...
5
votes
1answer
407 views

Soql-builder - Datetime issue

I have been trying to write a dynamic soql query by using soql-builder http://richardvanhook.com/2010/04/11/soql-builder/ But, I am stuck while assigning date as criteria while constructing the ...