1. A system for optimizing a query, comprising: a memory, and at least one processor operatively coupled to the memory; a construction module executed via the at least one processor and capable of building a data structure for a query, the data structure including a plurality of components, wherein each of the plurality of components corresponds to at least one graph pattern; a flow module executed via the at least one processor and capable of determining a plurality of flows of query variables between the plurality of components; a constraint module executed via the at least one processor and capable of generating one or more constraints to dynamically eliminate invalid flows from the plurality of flows, wherein a flow is determined to be invalid if the flow would violate semantics of one or more control statements in the query; and a cost determination and function module executed via the at least one processor and capable of: formulating a cost function associated with the plurality of flows; and outputting a query plan based on the cost function, wherein outputting the query plan comprises determining a combination of valid flows that results in a minimum cost under the one or more constraints.