>Should I create a PreparedStatement for the var SQL and nest it inside of SQL2
No
>Or should there be multiple PreparedStatements based on SQL2 without nesting
Yes
Furthermore: If you could create one string per query that would be better. I don't really like to mix SQL with code. It makes it harder to debug and to understand, you can't copy/paste to a SQL tool to test it easily. By separating the SQL from your code you'll isolate your query from the operation ( the actual fetch ) and it would be easier to maintain. Plus if the code is not yours it will be a lot easier to understand.
It doesn't matter it looks like your're repeating strings, the point would be to simplify the statements as much as possible.
I would do something like this:
final class DatabaseQueries {
public final static String SOME_SCENARIO = "SELECT z WHERE x > y JOIN A, B ";
public final static String SOME_OTHER_SCENARIO = "SELECT z WHERE x <= y JOIN A, B";
}
And then use it from your class:
PreparedStatement pstmt = getCon().prepareStatement( getQuery() );
private String getQuery() {
if( x != null ) {
return DatabaseQueries.SOME_SCENARIO;
} else {
return DatabaseQueries.SOME_OTHER_SCENARIO;
}
}
While creating the class "DatabaseQueries" you'll find you're repeating a lot of strings, I think it would be fine to susbtitute some part with other constants.
final class DataBaseQueries {
// this one is private
private final static String JOIN_A_B = " join A, B ";
public final static String SOME_SCENARIO = "SELECT z WHERE x > y " + JOIN_A_B ;
public final static String SOME_OTHER_SCENARIO = "SELECT z WHERE x <= y " + JOIN_A_B ;
}
The point here is to make things simpler. This is the first step. In a second step you can create a class to create those queries that are really really complex, but probably YAGNI.
If the queries are too much you can replace it to load them from a ResourceBundle like in this question
I hope this helps.