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);