viirya commented on a change in pull request #24344: [SPARK-27440][SQL] 
Optimize uncorrelated predicate subquery
URL: https://github.com/apache/spark/pull/24344#discussion_r276574876
 
 

 ##########
 File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala
 ##########
 @@ -551,3 +552,30 @@ object RewriteCorrelatedScalarSubquery extends 
Rule[LogicalPlan] {
       }
   }
 }
+
+/**
+ * This rule rewrites uncorrelated PredicateSubquery expressions such as 
Exists.
+ * The uncorrelated Exists can be evaluated using a subplan instead of a 
semi-join.
+ * Also, we can use `limit 1` and `select 1` after the subquery to reduce the 
result set.
+ * Example:
+ * exists(select b from t where t.a = 2) => exists(select 1 from t where t.a = 
2 limit 1)
+ */
+object RewriteUncorrelatedSubquery extends Rule[LogicalPlan] {
+  /**
+   * Wrap the subquery with `limit 1` and `project 1`.
+   */
+  def buildSubquery(sub: LogicalPlan): LogicalPlan = {
+    Project(Seq(Alias(Literal.create(1, IntegerType), "1")()),
+      Limit(Literal.create(1, IntegerType), sub))
+  }
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan transform {
+    case Filter(condition, child) =>
+      val newCondition = condition transform {
+        case Exists(sub, children, _) if children.isEmpty =>
 
 Review comment:
   Only deal with `Exists`? Will it process `InSubquery`?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to