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
shivshiv 

How to put an Id into a query manually

Hello, a basic question, how to put an Object Id manually into a select query
 
My problem is the following code shows error
 
System.QueryException: unexpected token: MqXA9AAN

Class.testApex.getA: line 4, column 19
External entry point
 
 
 
public class testApex {
    public Account getA(){
        Id id='0018000000MqXA9AAN';
        Account a=Database.query('select id,name from Account where id='+id);
        return a;
    }
}
 
 
I also tried to put '... where id=:id') .. It showed
 
System.QueryException: Binding not supported with dynamic SOQL

Class.testApex.getA: line 4, column 19
External entry point
 
Please provide me a solution
 
JimRaeJimRae
You have two choices, either don't use a dynamic query, and use this method:

Code:
public class testApex {
    public Account getA(){
        Id id='0018000000MqXA9AAN';
        Account a=[select id,name from Account where id=:id LIMIT 1];
        return a;
    }
}

or, build you full query string before submitting the query:
Code:
public class testApex {
    public Account getA(){
        String id='0018000000MqXA9AAN';
        String qs='select id,name from Account where id='+id+' LIMIT 1';
        Account a=Database.query(qs);
        return a;
    }
}

 
 

shivshiv
Hello jim, thanks for your reply..
 
I cant use the first choice you gave since the number of ids used in the query since the number of ids differ each time(dynamic)
 
And when i tried to use the second one its showing the following error
 
System.QueryException: unexpected token: MqXA9AAN

 
 
SuperfellSuperfell
the id needs single quotes around it, e.g. you need to generate this string.

select foo__c from bar__c where id='someId'
JimRaeJimRae
Sorry about that, forgot about the quotes.

generate your string like this: String qs='select id,name from Account where id=\''+id+'\' LIMIT 1';

Code:
Public class testApex {
    public Account getA(){
        String id='0018000000MqXA9AAN';
        String qs='select id,name from Account where id=\''+id+'\' LIMIT 1';
        Account a=Database.query(qs);
        return a;
    }
}