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

1.4K    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

Answers (6)

This is a common task in Salesforce development! For your CRM app, to fetch accounts sorted by name, you'll want to write a SOQL query like "SELECT Id, Name FROM Account ORDER BY Name ASC". It's a straightforward use of ORDER BY. Makes me think of how simple the snake game is, yet so engaging.



1 Week

Thinking about applying this to a Retro bowl football game scoring system, perhaps ordering players by touchdowns ksupport or completion rate.  

4 Months

Great SOQL guide! I always found ORDER BY helpful for Account queries, especially when needing to quickly sort leads. Granny used to say, 'Always put things in order!' Makes finding what you need so much easier, like locating that one specific field. Thanks for the clear explanation!



5 Months
Great explanation of using ORDER BY in SOQL for Salesforce Accounts! I found the example with different fields and sorting direction really helpful. Thinking about applying this to a Retro bowl football game scoring system, perhaps ordering players by touchdowns or completion rate. A clear and concise post!
9 Months
SELECT Name FROM Account ORDER BY Name ASCIt fetches account names sorted in ascending order. https://www.hhaexchange.com.co
10 Months

SOQL query using “ORDER BY” keyword to fetch this information from Salesforce “Account” Object is a natural thing to do. The program items you gave also Geometry Dash Lite match quite well.

1 Year

Interviews

Parent Categories