0

Below is the query I have used :-

User singleUser= [SELECT id,name,alias FROM user 
    WHERE alias = 'random' AND name = 'Random Name' LIMIT 1];

In the IF condition I want to check for the null condition for this SOQL query...like if this query has returned an empty result or not. How can i do that?

I have tried to put

system.debug('size ============= ' + singleUser.isblank());
system.debug('size ============= ' + singleUser.isempty());

But it throws me the error :-

Method does not exist or incorrect signature: void isblank() from the type User

1
  • User record (SObject) doesn't have any methods like isblank or isempty (which is apparent from the error message). You need to use "List<User> users" instead and then you can check using "users.isEmpty()".
    – arut
    Commented Aug 10, 2020 at 6:38

3 Answers 3

2

You are assigning the query result to sObject directly, which would work fine if the SOQL returns a result(single).

But, if there is no result you will get the below error:

List has no rows for assignment to SObject

Also, the User object(sObject) doesn't have methods isBlank and isEmpty, which are methods for list type.

So it would be safer to assign the SOQL result to a List variable, like:

List<User> userList = [SELECT id,name,alias FROM user WHERE alias = 'random' AND name = 'Random Name' LIMIT 1];

Post that, you can add a check on the list as given below

if(userList.isEmpty()) {
}

Refer this article for more details

1

You should use list to query the records instead of assigning the values to a sObject variable. It will throw QueryException if no records found.

List<User> singleUser= [SELECT id,name,alias FROM user WHERE alias = 'random' AND name = 'Random Name' LIMIT 1];
if(!singleUser.isEmpty()){
    //do the logic
    system.debug(singleUser[0].name); //Access the record value    
}

Also, There is no such method on isblank() or isEmpty() to check for sObject variable.


Or You can use this:- Check if object is null and return null

User singleUser; // is null
for(User record: [SELECT id,name,alias FROM user WHERE alias = 'random' AND name = 'Random Name' LIMIT 1]) {
  singleUser = record;
}

here, you can check:-

if(singleUser != null){
}
0

if you really need a user at this point in the code, you can also use a try & catch and in the catch you can show the user a message or just return as you can't continue without a user.

Checks for null or isBlank is only a good solution if you still have something todo when there is no user.

Otherwise I would do a try & catch with err-handling in the catch.

You must log in to answer this question.

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