Static and dynamic SOQL queries and best practices

If you are building Dynamic SOQL Queries that can be using for Apex Classes and Batch Apex you can use the Database.query(”) function to build the query:

      private static final String soqlQuery = 'Select id, OwnerId from Account';
      public void updateAccountOwnerByOwnerName(String currentOwnerName, String newOwnerName)
         Map<Account> updateAccountWithNewOwnerName = new Map();
         List<Account> accountsAssignedToCurrentOwner = Database.query(soqlQuery + ' where Owner.Name like \' currentOwnerName + \');
         User getNewOwnerId = new User(Name=newOwnerName);
         for (Account accountsToUpdateOwner : accountsAssignedToCurrentOwner)
           accountsToUpdateOwner.OwnerId = getNewOwnerId.Id;
           updateAccountWithNewOwnerName.put(accountsToUpdateOwner.OwnerId, accountsToUpdateOwner);
        update updateAccountWithNewOwnerName.values();

Non-dynamic soql or static soql looks like:

List<Account> accounts = [select id from account limit 100];

Apex Batch returns Database.QueryLocator or a Iterable.

private String query = 'Select id from Account';
return Database.getQueryLocator(query);

Combining non-dynamic SOQL with dynamic SOQL by converting from [ ] to a String. Using Database.getQueryLocator this can be done:

Database.getQueryLocator([select id from account] + ' where Owner.Name =' + newOwnerName);

2 thoughts on “Static and dynamic SOQL queries and best practices

  1. Une de ses meilleures performances sont venus aux Jeux olympiques d’été de 1988 quand elle a remporté le medal.

  2. Real Madrid: Casillas, Ronaldo, Carvajal, Pepe, Ramos, Marcelo, Kroos, Modric, Isco, Bale, BenzemaJames Rodriguez ne jouera pas pour le Real Madrid comme il est encore remis de son dommage4 de pied: 17:00 HNE: jeu begins4th minute: Luis Suarez et Sergio Ramos obtiennent dans confrontation6th minute: Karim Benzema manque de pied de but large de net12th minute: Cristiano Ronaldo tire un tir haut sur Claudio Bravo .

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s