1. A method for constructing an optimal representation for an input query, the method comprising: receiving the input query, wherein the input query is an intermediate language representation comprising nodes, each node having a respective node type; examining the nodes in a left-depth first manner to identify node types for optimization; tagging nodes corresponding to the identified node types; moving upward to the next node until the intermediate language representation of the input query has been examined in its entirety; searching from the top of the intermediate language representation for tagged nodes and identifying associated code patterns to be optimized; and adjusting the identified code patterns with improved code patterns to form an optimal representation for the input query.