1

I'm having trouble with my SOQL, running into SOQL limits in production. My SOQL is counting all active Users grouped by their Freeze status. How do I re-write the following SOQL without a subquery. Instead of a subquery I tried User.IsActive = true. That didn't work.

  SELECT count(Id) CountOfUsers,  IsFrozen FreezeStatus, max(LastModifiedDate) LastModified FROM UserLogin WHERE UserId IN 
                          (SELECT Id FROM User WHERE IsActive = true) group by IsFrozen.

Looks like the subquery is causing the max out eventhough I'm returning an aggregate of 2 rows.

0

1 Answer 1

1

The rows from your Left Inner Join do not count against your governors. If you're running into row limits, it is strictly because you have too many UserLogin records.

If you want to know the number of User records, query on User. You can use the same type of join, just in the other direction.

Integer frozenUserCount = [
    SELECT count() FROM User WHERE Id IN (
        SELECT UserId FROM UserLogin WHERE IsFrozen = true
    )
];
Datetime frozenLastModified = [
    SELECT LastModifiedDate
    FROM UserLogin
    WHERE IsFrozen = true
    ORDER BY LastModifiedDate DESC
    LIMIT 1
].LastModifiedDate;

Integer notFrozenUserCount = [
    SELECT count() FROM User WHERE Id IN (
        SELECT UserId FROM UserLogin WHERE IsFrozen = false
    )
];
Datetime notFrozenLastModified = [
    SELECT LastModifiedDate
    FROM UserLogin
    WHERE IsFrozen = false
    ORDER BY LastModifiedDate DESC
    LIMIT 1
].LastModifiedDate;
2
  • this is great! I didn't even think about this. When I tried executing the aggregate twice in anonymous apex, I was getting the SOQL limit warning. Even though the aggregate was returning 2 rows. When I ran the statement only once, I did not get the error. I was concerned we will reach the SOQL limit if we get more users. Commented Mar 15, 2018 at 22:55
  • @Donald even if there is only one AggregateResult, each record which goes into it is what gets added up for your governor usage.
    – Adrian Larson
    Commented Mar 15, 2018 at 22:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .