Below is my code:

  CustomObj obj = [Select id from CustomObj1];

How to find the size of the custom object "obj" using apex?

I tried using isEmpty() function but it shows compilation error as below

Compile Error: Method does not exist or incorrect signature

  • Can you explain it little more in detail. What you refer in the place of size ? Do you want to check is that your query returned data? or what you want to find ? – Monish Oct 29 '15 at 9:15
  • Or are you curious the actual heap space ("size") this object will take up? – pchittum Oct 29 '15 at 9:35

The expression:

[Select id from CustomObj1__c]

produces a list of CustomObj1. That code will never produce a null but it may produce an empty list. (Code should only include null checks where nulls can occur and they can't occur here.)

You can define a variable of the right list type using either of these syntaxes; the first one is a little shorter and looks a little more symmetrical:

CustomObj1__c[] objects = [Select id from CustomObj1__c];


List<CustomObj1__c> objects = [Select id from CustomObj1__c];

Once you have the objects variable, you can invoke any of the list methods on it including isEmpty() and size():

if (!objects.isEmpty()) {


if (objects.size() > 0) {

or better just:

for (CustomObj1__c o : objects) {

or even better just:

for (CustomObj1__c o : [
        Select id
        from CustomObj1__c
        ]) {

isEmpty() is an instance method of List class and Set class so if you need to check the size with that, first it needs to be a collection of data something like List or Set.

List<CustomObj> objList = [Select id from CustomObj1];

   Integer listSize = objList.size();

You can't apply isEmpty() on a sObject itself.

  • Suggest you remove the null check as null will never be returned. – Keith C Oct 29 '15 at 9:38
  • Agreed @KeithC, updated accordingly. – highfive Oct 29 '15 at 9:45

It is always a best practice to check for nullability on a variable that stores results from a soql query. Soql query will return null if no records exist or the criteria doesn't return any result.

In your case it will be as follows:

if(objList != null) { // check size}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.