1. A computer implemented method for optimizing database queries, the method comprising: receiving, by a database system, a database query for optimization, the database query comprising a first subquery and a second subquery, the first subquery specifying a first where clause comprising a first condition and the second subquery specifying a second where clause comprising a second condition, wherein the first where clause is distinct from the second where clause and wherein the first condition evaluates to true for a first set of input rows and the second condition evaluates to true for a second set of input rows; comparing the first subquery and the second subquery based on input tables processed by each of the first and second subqueries; responsive to determining that the first subquery and the second subquery match based on the comparison: generating a first database query specifying a where clause comprising a condition that evaluates to true for a superset of the first set of input rows and the second set of input rows; generating a statement comprising the first database query, the statement storing result of execution of the first database query in a result table; generating a first expression equivalent to the first subquery and a second expression equivalent to the second subquery, the first and the second expressions based on the result table; modifying the database query to use the result table, the modifying comprising, replacing the first subquery with the first expression and the second subquery with the second expression; and replacing an execution of the database query with an execution of the statement followed by an execution of the modified database query.