Question: I have a soql query inside my apex class : 

```
SELECT Id, Name, account.name, Special_food_requirements__c,Passport_number__c,account.Relationship__c,Function__c
                     FROM Contact
                     WHERE accountId IN :selectedAccountIds
                     AND Id Not IN(SELECT contact__c FROM Visit_contact__c WHERE Visit__c =:visitId)
                     order by account.Name ASC,Name ASC limit 1000

```

Soumetimes, for some users I get timeout. 

How can I fix it ? Thank you in advance !

Answer: 
Your query uses 'anti-patterns' and doesn't use indexed fields that's why it sometimes times out on you. The `Id Not IN(SELECT contact__c` is not an efficient way to query because it requires the SOQL engine to look through every record. On top of that you then use an ORDER BY clause that's 2 levels deep on fields that aren't indexed. The ORDER BY takes a lot of time for the query engine to perform, particularly since you're using fields from two different objects. While they're both indexed, the fact they're from different object likely makes it more difficult for the order by to take place. You might want to look at <https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_VLSQ.htm>
Avoid NOT IN for sure, but you can also set the Timeout depending on what language you are using. This is how in C# for example.

```
private static SforceService binding;

binding.QueryOptionsValue = new QueryOptions();
binding.QueryOptionsValue.batchSize = 2000;
binding.QueryOptionsValue.batchSizeSpecified = true;
binding.Timeout = 180000;

```