function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
eriktowneriktown 

Database query for "near matches"

Hello folks,

 

I want to allow users to search for contacts and leads in my app using a custom controller. So far I am able to have users search by the contact's email address using the following query syntax:

 

List<Contact> contacts = [select name from Contact where email=:email];

 

What I'm wondering is whether if the user enters a partial email address, will this query also return "similar" results? Is there a LIKE condition I can use as there is in standard SQL?

 

I'm also interested in applying this to user's names - if the user searches for the name "John", i'd like to return all contacts with the first name John.

 

Will this sort of syntax do what I want? The documentation on doing database queries from Apex hasn't been very clear.

 

Thanks!

Chamil MadusankaChamil Madusanka

Hi,

 

Use following statement.

 

List<Contact> contacts = [select name from Contact where email LIKE :('%'+email+'%')];

 If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

 

Chamil's Blog



Rahul SharmaRahul Sharma

I hope you are inputting the email and name from a vf page.

If its the case, then you can do this using dynamic formatting query in database.query :

Just an example to clear:

 

public pageReference search()
{
	oplist = new List<opportunity>();
	String strQueryCondition = '';

	if(obj.StartDate__c!= null)
	{
		strQueryCondition += 'StartDate__c = obj.StartDate__c ' ;
	}
	else If(obj.EndDate__c!= null)
	{
		if(strQueryCondition.contains('StartDate__c'))
			strQueryCondition += 'and EndDate__c = obj.EndDate__c ';
		else
			strQueryCondition += 'EndDate__c = obj.EndDate__c ';
	}
	else If(obj.StageName!= null)
	{
		if(strQueryCondition.contains('StartDate__c') || strQuery.contains('EndDate__c'))
			strQueryCondition += 'and StageName = obj.StageName ';
		else
			strQueryCondition += 'StageName = obj.StageName ';
	}
	if(strQueryCondition != null || strQueryCondition != '')
	{
		strQueryCondition = 'Where' + strQueryCondition;
	}
	oplist = Database.query('select Name from opportunity '+ strQueryCondition);
	return null;