How to write an SOQL query with "ORDER BY" for Salesforce "Account"?

233    Asked by CrownyHasegawa in Salesforce , Asked on Jun 21, 2024

 I am currently developing a customer relationship management application by using Salesforce. My application needs to display a list of accounts sorted by their account names in ascending order. How can I write a SOQL query by using the “ORDER BY” keyword for fetching this information from the Salesforce “Account” Object? 

Answered by Csaba Toth

In the context of Salesforce, here is the java-based example given below:-

Import com.sforce.soap.enterprise.Connector;
Import com.sforce.soap.enterprise.EnterpriseConnection;
Import com.sforce.soap.enterprise.QueryResult;
Import com.sforce.soap.enterprise.sobject.Account;
Import com.sforce.ws.ConnectorConfig;
Public class SalesforceQueryOrderByExample {
    Public static void main(String[] args) {
        // Salesforce credentials
        String username = “your_username”;
        String password = “your_password”;
        String securityToken = “your_security_token”;
        String authEndpoint = https://login.salesforce.com/services/Soap/c/52.0; // Adjust API version as needed
        Try {
            // Set up the connection configuration
            ConnectorConfig config = new ConnectorConfig();
            Config.setUsername(username);
            Config.setPassword(password + securityToken);
            Config.setAuthEndpoint(authEndpoint);
            // Create the connection
            EnterpriseConnection connection = Connector.newConnection(config);
            // Construct the SOQL query with ORDER BY clause
            String soqlQuery = “SELECT Id, Name, Industry FROM Account ORDER BY Name ASC”;
            // Execute the query
            QueryResult queryResult = connection.query(soqlQuery);
            // Process the query result
            If (queryResult.getSize() > 0) {
                System.out.println(“Accounts sorted by Name in ascending order:”);
                For (Account account : queryResult.getRecords()) {
                    System.out.println(“Account ID: “ + account.getId() + “, Name: “ + account.getName() + “, Industry: “ + account.getIndustry());
                }
            } else {
                System.out.println(“No accounts found.”);
            }
            // Close the connection
            Connection.logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Here is the python based example given below:-

From simple_salesforce import Salesforce
# Salesforce credentials
Username = ‘your_username’
Password = ‘your_password’
Security_token = ‘your_security_token’
Domain = ‘login’ # for production use ‘login’, for sandbox use ‘test’
# Initialize Salesforce connection
Sf = Salesforce(username=username, password=password, security_token=security_token, domain=domain)
# Define the SOQL query with ORDER BY clause
Soql_query = “SELECT Id, Name, Industry FROM Account ORDER BY Name ASC”
Try:
    # Execute the SOQL query
    Query_result = sf.query_all(query=soql_query)
    # Process the query result
    If query_result[‘totalSize’] > 0:
        Print(“Accounts sorted by Name in ascending order:”)
        For record in query_result[‘records’]:
            Account_id = record[‘Id’]
            Account_name = record[‘Name’]
            Account_industry = record[‘Industry’]
            Print(f”Account ID: {account_id}, Name: {account_name}, Industry: {account_industry}”)
    Else:
        Print(“No accounts found.”)
Except Exception as e:
    Print(f”An error occurred: {e}”)
# Logout from Salesforce (optional)
# sf.logout()

Here is the example given below in HTML:-


        Document.getElementById(‘soqlForm’).addEventListener(‘submit’, function(event) {            Event.preventDefault(); // Prevent the default form submission            Const query = document.getElementById(‘query’).value;            // Make AJAX request to execute the SOQL query
            Fetch(‘/execute_soql_query’, {
                Method: ‘POST’,
                Headers: {
                    ‘Content-Type’: ‘application/json’,
                },
                Body: JSON.stringify({ query: query }),
            })
            .then(response => response.json())
            .then(data => displayQueryResult(data))
            .catch(error => console.error(‘Error:’, error));
        });
        Function displayQueryResult(result) {
            Const queryResultDiv = document.getElementById(‘queryResult’);
            queryResultDiv[removed] = ‘’; // Clear previous results
            if (result.totalSize > 0) {
                const records = result.records;
                const resultList = document.createElement(‘ul’);
                records.forEach(record => {
                    const listItem = document.createElement(‘li’);
                    listItem.textContent = `Account ID: ${record.Id}, Name: ${record.Name}, Industry: ${record.Industry}`;
                    resultList.appendChild(listItem);
                });                queryResultDiv.appendChild(resultList);
            } else {
                queryResultDiv.textContent = ‘No accounts found.’;
            }
        }   



Your Answer

Interviews

Parent Categories