query()

Executes a query against the specified object and returns data that matches the specified criteria.

Syntax

QueryResult = connection.query(string queryString);

Usage

Use the query() call to retrieve data from an object. When a client application invokes the query() call, it passes in a query expression that specifies the object to query, the fields to retrieve, and any conditions that determine whether a given object qualifies. For an extensive discussion about the syntax and rules used for queries, see the Salesforce SOQL and SOSL Reference Guide.

Upon invocation, the API executes the query against the specified object, caches the results of the query on the API, and returns a query response object to the client application. The client application can then use methods on the query response object to iterate through rows in the query response and retrieve information.

Your client application must be logged in with sufficient access rights to query individual objects within the specified object and to query the fields in the specified field list. For more information, see Factors that Affect Data Access.

Certain objects cannot be queried via the API. To query an object via the query() call, its object must be configured as queryable. To determine whether an object can be queried, your client application can invoke the describeSObjects() call on the object and inspect its queryable property.

Tip
If you use the enterprise WSDL, you should not use describe to populate a select list. For example, if a system administrator adds a field to the SObject after you consume it, the describe call will pull down the field but your toolkit won’t know how to serialize it, and your integration may fail.

You can use queryAll() to query on all Task and Event records, archived or not. You can also filter on the isArchived field to find only the archived objects. You cannot use query(), it automatically filters out all records where isArchived is set to true. You can insert, update, or delete archived records.

The query result object contains up to 500 rows of data by default. If the query results exceed 500 rows, then the client application uses the queryMore() call and a server-side cursor to retrieve additional rows in 500-row chunks. You can increase the default size up to 2,000 in the QueryOptions header. For more details see Change the Batch Size in Queries in the Force.com SOQL and SOSL Reference.

Queries that take longer than two minutes to process will be timed out. For timed out queries, the API returns an API fault element of InvalidQueryLocatorFault. If a timeout occurs, refactor your query to return or scan a smaller amount of data.

When querying for fields of type Base64 (see base64), the query response object returns only one record at a time. You cannot alter this by changing the batch size of the query() call.

Note
For multicurrency organizations, special handling is required when querying currency fields containing values in different currencies. For example, if a client application is querying PricebookEntry objects based on values in the UnitPrice field, and if the UnitPrice amounts are expressed in different currencies, then the query logic must handle this case correctly. For example, if the query is trying to retrieve the product codes of all products with a unit price greater than or equal to $10 USD, the query expression might look something like this:
SELECT Product2Id,ProductCode,UnitPrice FROM PricebookEntry 
WHERE (UnitPrice >= 10 and CurrencyIsoCode='USD') 
OR (UnitPrice >= 5.47 and CurrencyIsoCode='GBP')
OR (UnitPrice >= 8.19 and CurrencyIsoCode='EUR')

Sample Code—Java

This sample executes a query that fetches the first names and last names of all contacts. It calls query() with the query string to get the first batch of records. It then calls queryMore() in a loop to get subsequent batches of records until no records are returned. It writes the first and last names of the contacts queried to the console.

public void queryRecords() {
   QueryResult qResult = null;
   try {
      String soqlQuery = "SELECT FirstName, LastName FROM Contact";
      qResult = connection.query(soqlQuery);
      boolean done = false;
      if (qResult.getSize() > 0) {
         System.out.println("Logged-in user can see a total of "
            + qResult.getSize() + " contact records.");
         while (!done) {
            SObject[] records = qResult.getRecords();
            for (int i = 0; i < records.length; ++i) {
               Contact con = (Contact) records[i];
               String fName = con.getFirstName();
               String lName = con.getLastName();
               if (fName == null) {
                  System.out.println("Contact " + (i + 1) + ": " + lName);
               } else {
                  System.out.println("Contact " + (i + 1) + ": " + fName
                        + " " + lName);
               }
            }
            if (qResult.isDone()) {
               done = true;
            } else {
               qResult = connection.queryMore(qResult.getQueryLocator());
            }
         }
      } else {
         System.out.println("No records found.");
      }
      System.out.println("\nQuery succesfully executed.");
   } catch (ConnectionException ce) {
      ce.printStackTrace();
   }
}

Sample Code—C#

This sample executes a query that fetches the first names and last names of all contacts. It calls query() with the query string to get the first batch of records. It then calls queryMore() in a loop to get subsequent batches of records until no records are returned. It writes the first and last names of the contacts queried to the console.

public void queryRecords()
{
   QueryResult qResult = null;
   try
   {
      String soqlQuery = "SELECT FirstName, LastName FROM Contact";
      qResult = binding.query(soqlQuery);
      Boolean done = false;
      if (qResult.size > 0)
      {
         Console.WriteLine("Logged-in user can see a total of "
            + qResult.size + " contact records.");
         while (!done)
         {
            sObject[] records = qResult.records;
            for (int i = 0; i < records.Length; ++i)
            {
               Contact con = (Contact)records[i];
               String fName = con.FirstName;
               String lName = con.LastName;
               if (fName == null)
               {
                  Console.WriteLine("Contact " + (i + 1) + ": " + lName);
               }
               else
               {
                  Console.WriteLine("Contact " + (i + 1) + ": " + fName
                        + " " + lName);
               }
            }
            if (qResult.done)
            {
               done = true;
            }
            else
            {
               qResult = binding.queryMore(qResult.queryLocator);
            }
         }
      }
      else
      {
         Console.WriteLine("No records found.");
      }
      Console.WriteLine("\nQuery succesfully executed.");
   }
   catch (SoapException e)
   {
      Console.WriteLine("An unexpected error has occurred: " +
                                 e.Message + "\n" + e.StackTrace);
   }
}

Arguments

Name Type Description
queryString string Query string that specifies the object to query, the fields to return, and any conditions for including a specific object in the query. For more information, see the Salesforce SOQL and SOSL Reference Guide.

Response

QueryResult

Faults

MalformedQueryFault

InvalidSObjectFault

InvalidFieldFault

UnexpectedErrorFault

© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.