function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yogesh BiyaniYogesh Biyani 

queryCount fails with Use query() for non-count queries

I am using a dynamic query but it fails with Use query() for non-count queries . What am I missing? 
 
for(Schema.ChildRelationship child : dsr.getChildRelationships()) {
String query=  'select count(id) FROM CONTACT WHERE ID NOT IN (SELECT '+
            	child.getField()+' FROM '+child.getChildSObject()+ ')'; 

        integer  t=Database.countquery(query);
system.debug(t);
}

 
Yogesh BiyaniYogesh Biyani
When I change the query to the following  Database.countquery fails with Too Many Query Rows 50001
String query=  'select count() FROM '+child.getChildSObject();

Will greatly appreciate if someone can help. 

Thanks in advance.

Yogesh

 
Abdul KhatriAbdul Khatri
What is your goal? You are just trying to throw the SOQL with all the LIMITS?

To me it seems like you are trying to get the Count of the Contact but Id you matching with getField. I am kind of the lost of what exactly you wanted.
Abdul KhatriAbdul Khatri
Hi please provide some details so that better solution be worked on.
SharadDhaliaSharadDhalia
Hi,

This is because return type of Database.countquery is Integer where as with COUNT(Id) return type is AggregateResult.
Below should work just fine:

for(Schema.ChildRelationship child : dsr.getChildRelationships()) {
String query= 'select count() FROM CONTACT WHERE ID NOT IN (SELECT '+ child.getField()+' FROM '+child.getChildSObject()+ ')';
integer t=Database.countquery(query);
system.debug(t);
}

Thanks