How do you make long SQL invoked from other code readable?
Posted
by Artem
on Stack Overflow
See other posts from Stack Overflow
or by Artem
Published on 2010-05-05T16:38:55Z
Indexed on
2010/05/05
16:48 UTC
Read the original article
Hit count: 141
This is a very open question, but I think it can be very beneficial for SQL readability.
So you have a Java program, and you are trying to call a monster SQL statement from it, with many subqueries and joins. The starting point for my question is a string constant like this:
static string MONSTER_STATEMENT =
"SELECT " +
" fields" +
"WHERE "+
" fieldA = (SELECT a FROM TableC) " +
"AND fieldB IN (%s)" +
"AND fieldC = %d " +
"FROM "
" tableA INNER JOIN tableB ON ...";
It later gets filled using String.format and executed.
What are you tricks for making this kind of stuff readable? Do you separate your inner joins. Do you indent the SQL itself inside the string? Where do you put the comments? Please share all of the tricks in your arsenal.
© Stack Overflow or respective owner