You can evaluate Salesforce.com Object Query Language (SOQL) or Salesforce.com Object Search Language (SOSL) statements on-the-fly in Apex by surrounding the statement in square brackets.
SOQL statements evaluate to a list of sObjects, a single sObject, or an Integer for count method queries.
List<Account> aa = [select id, name from account where name = 'Acme'];
if (!aa.isEmpty()) { // Execute commands }
Contact c = new Contact(account = [select name from account where NumberofEmployees > 10 limit 1]); c.FirstName = 'James'; c.LastName = 'Yoyce';
Integer i = [select count() from contact where lastname = 'Weissman'];
Integer j = 5 * [select count() from account];
For a full description of SOQL query syntax, see Salesforce.com Object Query Language (SOQL) in the Force.com Web Services API Developer's Guide.
SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query. SOSL queries are only supported in Apex classes and anonymous blocks. You cannot use a SOSL query in a trigger. If a SOSL query does not return any records for a specified sObject type, the search results include an empty list for that sObject.
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (id, name), Contact, Opportunity, Lead];
Account [] accounts = ((List<Account>)searchList[0]); Contact [] contacts = ((List<Contact>)searchList[1]); Opportunity [] opportunities = ((List<Opportunity>)searchList[2]); Lead [] leads = ((List<Lead>)searchList[3]);
For a full description of SOSL query syntax, see Salesforce.com Object Search Language (SOSL) in the Force.com Web Services API Developer's Guide.