Format a SQL String nicely (and simply)

After playing with regular expressions in notepad+, we were writing some tests around a SQL based query language and wanted to print out the queries nicely.

We came up with the remarkably simply yet effective use of String.replace() to create the following:


     String querystring = getSomeQueryString();
     System.out.println(queryString
                .replaceAll("WHERE", "\\nWHERE")
                .replaceAll("AND", "\\n\\tAND")
                .replaceAll("OR", "\\n\\t\\tOR"));

Well it worked for ours, think might need some adjustment for different OR / AND structures.

  • Share/Bookmark