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 cost determination and ranking module executed via the at least one processor and capable of determining a combination of the plurality of flows between the plurality of components that results in a minimum cost to execute the query; and a constraint module executed via the at least one processor and capable of generating one or more constraints for ruling out invalid flows of the plurality of flows; wherein the plurality of constraints comprise a component constraint enforcing semantics of an external view of one or more of the components, a graph constraint enforcing semantics of the plurality of flows of query variables, and a predecessor constraint enforcing semantics of one or more potential predecessors.