Tutorial by Examples

SELECT Id, Name FROM Account This will return the Id and Name fields from the Account table. No filtering or sorting will be applied.
SELECT Name FROM User WHERE IsActive = true This will return the name of all active Users. SELECT Name, Phone FROM Contact WHERE CreatedDate >= 2016-01-01T00:00:00.000Z This will return Contacts created on or after January 1st, 2016. SELECT Id, Name FROM Account LIMIT 100 This will ret...
SELECT Id, Name FROM User ORDER BY LastName SELECT Id, Name FROM Contact ORDER BY LastModifiedDate DESC SELECT Name, Title FROM User ORDER BY Title ASC NULLS FIRST SELECT Id FROM Contact ORDER BY LastName ASC NULLS LAST, FirstName ASC NULLS FIRST
A very useful feature many people overlook is the ability to construct a Map using a SOQL query. Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id, Name FROM Account]); System.debug(accounts); When you run this code, accounts then contains a Map of your Account objects, ke...
When object's are linked by a lookup or master-detail relationship, the parent records field's can be referenced from the child record or 'base object' in a query. This is also known as upwards traversal. SELECT FirstName, Account.Name, Account.Category__c FROM Contact It's possible to traverse ...
To perform a query in Apex, surround the query with square brackets. The result can be assigned to a list, or to a single object. List<Account> allAccounts = [SELECT Id, Name FROM Account]; Account oldestAccount = [SELECT Id, Name FROM Account ORDER BY CreatedDate LIMIT 1];
To reference a variable in a query, add a colon (:) before the variable name. Datetime targetDate = Datetime.now().addDays(-7); List<Lead> recentLeads = [SELECT Id FROM Lead WHERE CreatedDate > :targetDate]; string targetName = 'Unknown'; List<Contact> incompleteContacts = [SELE...
When assigning to a single object, a query that returns anything other than a single row will throw a QueryException. try { Account a = [SELECT Id FROM Account WHERE Name = 'Non-existent Account']; } catch (QueryException e) { // List has no rows for assignment to SObject } try { ...
Selecting all accounts that have open opportunity records under them SELECT Id, Name FROM Account WHERE AccountId IN (SELECT Id FROM Opportunity WHERE IsClosed = false)
You can execute a database query from a String rather than a regular SOQL expression: String tableName = 'Account'; String queryString = 'SELECT Id FROM ' + tableName + ' WHERE CreatedDate >= YESTERDAY'; List<SObject> objects = Database.query(queryString); Since dynamic SOQL queries a...

Page 1 of 1