This is an automated email from the ASF dual-hosted git repository.

rubenada pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/calcite.git


The following commit(s) were added to refs/heads/main by this push:
     new 67b7c6cea0 [CALCITE-7815] Support the SQL-standard SEARCH clause in 
recursive CTEs
67b7c6cea0 is described below

commit 67b7c6cea08ab814ac86079635143e3a3e8f4031
Author: Vladislav Pyatkov <[email protected]>
AuthorDate: Thu Oct 29 18:08:08 2026 +0300

    [CALCITE-7815] Support the SQL-standard SEARCH clause in recursive CTEs
---
 core/src/main/codegen/templates/Parser.jj          |  26 +-
 .../calcite/adapter/enumerable/RexImpTable.java    |   4 +-
 .../apache/calcite/runtime/CalciteResource.java    |  21 +-
 .../main/java/org/apache/calcite/sql/SqlKind.java  |   5 +-
 .../org/apache/calcite/sql/SqlSearchClause.java    | 106 +++++++
 .../java/org/apache/calcite/sql/SqlWithItem.java   |  25 +-
 .../calcite/sql/fun/SqlInternalOperators.java      |   6 +-
 ...cleRewriter.java => RecursiveWithRewriter.java} | 259 +++++++++++++----
 .../calcite/sql/validate/SqlValidatorImpl.java     |  13 +-
 .../calcite/runtime/CalciteResource.properties     |  10 +-
 .../apache/calcite/sql/SqlCallOperandsTest.java    |  63 +++++
 .../org/apache/calcite/test/RecursiveCteTest.java  | 279 +++++++++++++++++-
 core/src/test/resources/sql/recursive_queries.iq   | 314 +++++++++++++++++++++
 site/_docs/reference.md                            |  54 ++++
 .../apache/calcite/sql/parser/SqlParserTest.java   |  75 +++++
 15 files changed, 1167 insertions(+), 93 deletions(-)

diff --git a/core/src/main/codegen/templates/Parser.jj 
b/core/src/main/codegen/templates/Parser.jj
index f3d5a9396e..97dcd738e5 100644
--- a/core/src/main/codegen/templates/Parser.jj
+++ b/core/src/main/codegen/templates/Parser.jj
@@ -109,6 +109,7 @@ import org.apache.calcite.sql.SqlWindow;
 import org.apache.calcite.sql.SqlWith;
 import org.apache.calcite.sql.SqlWithItem;
 import org.apache.calcite.sql.SqlCycleClause;
+import org.apache.calcite.sql.SqlSearchClause;
 import org.apache.calcite.sql.fun.SqlCase;
 import org.apache.calcite.sql.fun.SqlInternalOperators;
 import org.apache.calcite.sql.fun.SqlLibraryOperators;
@@ -4162,6 +4163,7 @@ void AddWithItem(List<SqlWithItem> list, SqlLiteral 
recursive) :
     final SqlIdentifier id;
     final SqlNodeList columnList;
     final SqlNode definition;
+    SqlSearchClause search = null;
     SqlCycleClause cycle = null;
 }
 {
@@ -4169,8 +4171,30 @@ void AddWithItem(List<SqlWithItem> list, SqlLiteral 
recursive) :
     ( columnList = ParenthesizedSimpleIdentifierList() | { columnList = null; 
} )
     <AS>
     definition = ParenthesizedExpression(ExprContext.ACCEPT_QUERY)
+    [ search = SearchClause() ]
     [ cycle = CycleClause() ]
-    { list.add(new SqlWithItem(id.getParserPosition(), id, columnList, 
definition, recursive, cycle)); }
+    { list.add(new SqlWithItem(id.getParserPosition(), id, columnList, 
definition, recursive,
+        search, cycle)); }
+}
+
+SqlSearchClause SearchClause() :
+{
+    final Span s;
+    final SqlSearchClause.SearchMode mode;
+    final List<SqlNode> columns = new ArrayList<SqlNode>();
+    SqlIdentifier column;
+    final SqlIdentifier orderColumn;
+}
+{
+    <SEARCH> { s = span(); }
+    ( <DEPTH> { mode = SqlSearchClause.SearchMode.DEPTH; }
+    | <BREADTH> { mode = SqlSearchClause.SearchMode.BREADTH; } )
+    <FIRST> <BY>
+    column = SimpleIdentifier() { columns.add(column); }
+    ( <COMMA> column = SimpleIdentifier() { columns.add(column); } )*
+    <SET> orderColumn = SimpleIdentifier()
+    { return new SqlSearchClause(s.end(this), SqlLiteral.createSymbol(mode, 
s.pos()),
+        new SqlNodeList(columns, s.pos()), orderColumn); }
 }
 
 SqlCycleClause CycleClause() :
diff --git 
a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java 
b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
index eabb37a923..8d06b11938 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
@@ -130,9 +130,9 @@
 import static org.apache.calcite.linq4j.tree.ExpressionType.Subtract;
 import static org.apache.calcite.linq4j.tree.ExpressionType.SubtractChecked;
 import static org.apache.calcite.linq4j.tree.ExpressionType.UnaryPlus;
-import static 
org.apache.calcite.sql.fun.SqlInternalOperators.CYCLE_PATH_APPEND;
 import static 
org.apache.calcite.sql.fun.SqlInternalOperators.CYCLE_PATH_CONTAINS;
 import static org.apache.calcite.sql.fun.SqlInternalOperators.LITERAL_AGG;
+import static 
org.apache.calcite.sql.fun.SqlInternalOperators.RECURSIVE_PATH_APPEND;
 import static org.apache.calcite.sql.fun.SqlInternalOperators.THROW_UNLESS;
 import static org.apache.calcite.sql.fun.SqlLibraryOperators.ACOSD;
 import static org.apache.calcite.sql.fun.SqlLibraryOperators.ACOSH;
@@ -1110,7 +1110,7 @@ void populate2() {
       defineMethod(STRUCT_ACCESS, BuiltInMethod.STRUCT_ACCESS.method, 
NullPolicy.SEMI_STRICT);
       defineMethod(MEMBER_OF, BuiltInMethod.MEMBER_OF.method, NullPolicy.NONE);
       defineMethod(ARRAY_APPEND, BuiltInMethod.ARRAY_APPEND.method, 
NullPolicy.ARG0);
-      defineMethod(CYCLE_PATH_APPEND, BuiltInMethod.ARRAY_APPEND.method, 
NullPolicy.ARG0);
+      defineMethod(RECURSIVE_PATH_APPEND, BuiltInMethod.ARRAY_APPEND.method, 
NullPolicy.ARG0);
       defineMethod(CYCLE_PATH_CONTAINS, 
BuiltInMethod.CYCLE_PATH_CONTAINS.method, NullPolicy.NONE);
       defineMethod(ARRAY_COMPACT, BuiltInMethod.ARRAY_COMPACT.method, 
NullPolicy.STRICT);
       defineMethod(ARRAY_CONTAINS, BuiltInMethod.ARRAY_CONTAINS.method, 
NullPolicy.SEMI_STRICT);
diff --git a/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java 
b/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
index 2ce43a1419..e89a0882be 100644
--- a/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
+++ b/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
@@ -956,20 +956,21 @@ ExInst<CalciteException> 
illegalArgumentForTableFunctionCall(String a0,
   @BaseMessage("A recursive query only supports binary UNION [ALL] operator")
   ExInst<SqlValidatorException> recursiveWithMustHaveTwoChildUnionSetOp();
 
-  @BaseMessage("CYCLE requires WITH RECURSIVE")
-  ExInst<SqlValidatorException> cycleRequiresRecursive();
+  @BaseMessage("{0} requires WITH RECURSIVE")
+  ExInst<SqlValidatorException> recursiveClauseRequiresRecursive(String 
clause);
 
-  @BaseMessage("CYCLE requires a UNION [ALL] with a recursive SELECT 
containing exactly one direct reference to its WITH item")
-  ExInst<SqlValidatorException> cycleRequiresRecursiveSelect();
+  @BaseMessage("{0} requires a UNION [ALL] with a recursive SELECT containing 
exactly one direct reference to its WITH item")
+  ExInst<SqlValidatorException> recursiveClauseRequiresRecursiveSelect(String 
clause);
 
-  @BaseMessage("CYCLE is not supported with aggregation, DISTINCT, or window 
functions in the recursive SELECT")
-  ExInst<SqlValidatorException> cycleRecursiveSelectNotSupported();
+  @BaseMessage("{0} is not supported with aggregation, DISTINCT, or window 
functions in the recursive SELECT")
+  ExInst<SqlValidatorException> recursiveClauseSelectNotSupported(String 
clause);
 
-  @BaseMessage("CYCLE column ''{0}'' is not a column of WITH item ''{1}''")
-  ExInst<SqlValidatorException> cycleColumnNotFound(String column, String 
withItem);
+  @BaseMessage("{0} column ''{1}'' is not a column of WITH item ''{2}''")
+  ExInst<SqlValidatorException> recursiveClauseColumnNotFound(String clause,
+      String column, String withItem);
 
-  @BaseMessage("CYCLE generated column ''{0}'' conflicts with another column")
-  ExInst<SqlValidatorException> cycleColumnConflict(String column);
+  @BaseMessage("{0} generated column ''{1}'' conflicts with another column")
+  ExInst<SqlValidatorException> recursiveClauseColumnConflict(String clause, 
String column);
 
   @BaseMessage("CYCLE mark and default must be distinct, non-null Boolean or 
compatible single-character string literals")
   ExInst<SqlValidatorException> cycleInvalidMarkValues();
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlKind.java 
b/core/src/main/java/org/apache/calcite/sql/SqlKind.java
index fd23a131a0..25ca817d53 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlKind.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlKind.java
@@ -209,6 +209,9 @@ public enum SqlKind {
   /** CYCLE clause of a recursive WITH item. */
   CYCLE,
 
+  /** SEARCH clause of a recursive WITH item (not the scalar SEARCH operator). 
*/
+  SEARCH_CLAUSE,
+
   /** Represents a recursive CTE as a table ref. */
   WITH_ITEM_TABLE_REF,
 
@@ -1528,7 +1531,7 @@ public enum SqlKind {
                   LITERAL_CHAIN, JDBC_FN, PRECEDING, FOLLOWING, ORDER_BY,
                   ORDER_BY_ALL, FROM_QUERY, PIPE_CALL, PIPE_INPUT,
                   NULLS_FIRST, NULLS_LAST, COLLECTION_TABLE, TABLESAMPLE,
-                  VALUES, WITH, WITH_ITEM, CYCLE, ITEM, SKIP_TO_FIRST, 
SKIP_TO_LAST,
+                  VALUES, WITH, WITH_ITEM, CYCLE, SEARCH_CLAUSE, ITEM, 
SKIP_TO_FIRST, SKIP_TO_LAST,
                   JSON_VALUE_EXPRESSION, UNNEST),
               SET_QUERY, AGGREGATE, DML, DDL));
 
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlSearchClause.java 
b/core/src/main/java/org/apache/calcite/sql/SqlSearchClause.java
new file mode 100644
index 0000000000..a6688d5214
--- /dev/null
+++ b/core/src/main/java/org/apache/calcite/sql/SqlSearchClause.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.sql;
+
+import org.apache.calcite.sql.parser.SqlParserPos;
+
+import com.google.common.collect.ImmutableList;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+import java.util.List;
+
+import static java.util.Objects.requireNonNull;
+
+/** SQL-standard search ordering clause of a recursive common table expression.
+ *
+ * <p>Syntax: {@code SEARCH { DEPTH | BREADTH } FIRST BY columns SET 
orderColumn}.
+ * The generated column is available to consumers of the WITH item; an explicit
+ * ORDER BY is needed to return rows in search order. */
+public class SqlSearchClause extends SqlCall {
+  private static final SqlSpecialOperator OPERATOR =
+      new SqlSpecialOperator("SEARCH", SqlKind.SEARCH_CLAUSE) {
+        @Override public SqlCall createCall(@Nullable SqlLiteral qualifier,
+            SqlParserPos pos, @Nullable SqlNode... operands) {
+          return new SqlSearchClause(pos,
+              (SqlLiteral) requireNonNull(operands[0]),
+              (SqlNodeList) requireNonNull(operands[1]),
+              (SqlIdentifier) requireNonNull(operands[2]));
+        }
+      };
+
+  /** Traversal order represented by the generated search key. */
+  public enum SearchMode implements Symbolizable {
+    DEPTH, BREADTH
+  }
+
+  public SqlLiteral mode;
+  public SqlNodeList columns;
+  public SqlIdentifier orderColumn;
+
+  public SqlSearchClause(SqlParserPos pos, SqlLiteral mode,
+      SqlNodeList columns, SqlIdentifier orderColumn) {
+    super(pos);
+    this.mode = mode;
+    this.columns = columns;
+    this.orderColumn = orderColumn;
+  }
+
+  @Override public SqlOperator getOperator() {
+    return OPERATOR;
+  }
+
+  /** Returns the search mode. */
+  public SearchMode getSearchMode() {
+    return mode.getValueAs(SearchMode.class);
+  }
+
+  @Override public List<SqlNode> getOperandList() {
+    return ImmutableList.of(mode, columns, orderColumn);
+  }
+
+  @Override public void setOperand(int i, @Nullable SqlNode operand) {
+    requireNonNull(operand, "operand");
+    switch (i) {
+    case 0:
+      mode = (SqlLiteral) operand;
+      break;
+    case 1:
+      columns = (SqlNodeList) operand;
+      break;
+    case 2:
+      orderColumn = (SqlIdentifier) operand;
+      break;
+    default:
+      throw new AssertionError(i);
+    }
+  }
+
+  @Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) 
{
+    writer.keyword("SEARCH");
+    writer.keyword(getSearchMode().name());
+    writer.keyword("FIRST BY");
+    final SqlWriter.Frame frame = writer.startList("", "");
+    for (SqlNode column : columns) {
+      writer.sep(",");
+      column.unparse(writer, 0, 0);
+    }
+    writer.endList(frame);
+    writer.keyword("SET");
+    orderColumn.unparse(writer, 0, 0);
+  }
+}
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlWithItem.java 
b/core/src/main/java/org/apache/calcite/sql/SqlWithItem.java
index cee07fbece..9dfca9e1be 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlWithItem.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlWithItem.java
@@ -23,15 +23,18 @@
 
 import java.util.List;
 
+import static com.google.common.base.Preconditions.checkArgument;
+
 /**
  * An item in a WITH clause of a query.
- * It has a name, an optional column list, a query, and an optional CYCLE 
clause.
+ * It has a name, an optional column list, a query, and optional SEARCH and 
CYCLE clauses.
  */
 public class SqlWithItem extends SqlCall {
   public SqlIdentifier name;
   public @Nullable SqlNodeList columnList; // may be null
   public SqlLiteral recursive;
   public SqlNode query;
+  public @Nullable SqlSearchClause searchClause;
   public @Nullable SqlCycleClause cycleClause;
 
   @Deprecated // to be removed before 2.0
@@ -44,17 +47,19 @@ public SqlWithItem(SqlParserPos pos, SqlIdentifier name,
   public SqlWithItem(SqlParserPos pos, SqlIdentifier name,
       @Nullable SqlNodeList columnList, SqlNode query,
       SqlLiteral recursive) {
-    this(pos, name, columnList, query, recursive, null);
+    this(pos, name, columnList, query, recursive, null, null);
   }
 
   public SqlWithItem(SqlParserPos pos, SqlIdentifier name,
       @Nullable SqlNodeList columnList, SqlNode query,
-      SqlLiteral recursive, @Nullable SqlCycleClause cycleClause) {
+      SqlLiteral recursive, @Nullable SqlSearchClause searchClause,
+      @Nullable SqlCycleClause cycleClause) {
     super(pos);
     this.name = name;
     this.columnList = columnList;
     this.recursive = recursive;
     this.query = query;
+    this.searchClause = searchClause;
     this.cycleClause = cycleClause;
   }
 
@@ -66,7 +71,7 @@ public SqlWithItem(SqlParserPos pos, SqlIdentifier name,
 
   @SuppressWarnings("nullness")
   @Override public List<SqlNode> getOperandList() {
-    return ImmutableNullableList.of(name, columnList, query, recursive, 
cycleClause);
+    return ImmutableNullableList.of(name, columnList, query, recursive, 
searchClause, cycleClause);
   }
 
   @SuppressWarnings("assignment.type.incompatible")
@@ -85,6 +90,9 @@ public SqlWithItem(SqlParserPos pos, SqlIdentifier name,
       recursive = (SqlLiteral) operand;
       break;
     case 4:
+      searchClause = (SqlSearchClause) operand;
+      break;
+    case 5:
       cycleClause = (SqlCycleClause) operand;
       break;
     default:
@@ -122,6 +130,9 @@ private static class SqlWithItemOperator extends 
SqlSpecialOperator {
       }
       writer.keyword("AS");
       withItem.query.unparse(writer, MDX_PRECEDENCE, MDX_PRECEDENCE);
+      if (withItem.searchClause != null) {
+        withItem.searchClause.unparse(writer, 0, 0);
+      }
       if (withItem.cycleClause != null) {
         withItem.cycleClause.unparse(writer, 0, 0);
       }
@@ -131,10 +142,12 @@ private static class SqlWithItemOperator extends 
SqlSpecialOperator {
     @Override public SqlCall createCall(@Nullable SqlLiteral functionQualifier,
         SqlParserPos pos, @Nullable SqlNode... operands) {
       assert functionQualifier == null;
-      assert operands.length == 4 || operands.length == 5;
+      checkArgument(operands.length == 4 || operands.length == 6,
+          "Expected 4 or 6 operands, got %s", operands.length);
       return new SqlWithItem(pos, (SqlIdentifier) operands[0],
           (SqlNodeList) operands[1], operands[2], (SqlLiteral) operands[3],
-          operands.length == 5 ? (SqlCycleClause) operands[4] : null);
+          operands.length == 6 ? (SqlSearchClause) operands[4] : null,
+          operands.length == 6 ? (SqlCycleClause) operands[5] : null);
     }
   }
 }
diff --git 
a/core/src/main/java/org/apache/calcite/sql/fun/SqlInternalOperators.java 
b/core/src/main/java/org/apache/calcite/sql/fun/SqlInternalOperators.java
index 5f798876ae..c586e9cd88 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlInternalOperators.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlInternalOperators.java
@@ -49,9 +49,9 @@ public abstract class SqlInternalOperators {
   private SqlInternalOperators() {
   }
 
-  /** Appends a key tuple to the path of a recursive CTE. */
-  public static final SqlInternalOperator CYCLE_PATH_APPEND =
-      new SqlInternalOperator("$CYCLE_PATH_APPEND", SqlKind.OTHER_FUNCTION,
+  /** Appends a key tuple to a recursive CTE path used by SEARCH or CYCLE. */
+  public static final SqlInternalOperator RECURSIVE_PATH_APPEND =
+      new SqlInternalOperator("$RECURSIVE_PATH_APPEND", SqlKind.OTHER_FUNCTION,
           2, true, ReturnTypes.ARG0, null, OperandTypes.ANY_ANY);
 
   /** Tests whether a key tuple occurs in a recursive CTE's path. */
diff --git 
a/core/src/main/java/org/apache/calcite/sql/validate/CycleRewriter.java 
b/core/src/main/java/org/apache/calcite/sql/validate/RecursiveWithRewriter.java
similarity index 60%
rename from 
core/src/main/java/org/apache/calcite/sql/validate/CycleRewriter.java
rename to 
core/src/main/java/org/apache/calcite/sql/validate/RecursiveWithRewriter.java
index 91c26e36e8..68166ba267 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/CycleRewriter.java
+++ 
b/core/src/main/java/org/apache/calcite/sql/validate/RecursiveWithRewriter.java
@@ -27,6 +27,7 @@
 import org.apache.calcite.sql.SqlLiteral;
 import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.SqlNodeList;
+import org.apache.calcite.sql.SqlSearchClause;
 import org.apache.calcite.sql.SqlSelect;
 import org.apache.calcite.sql.SqlUtil;
 import org.apache.calcite.sql.SqlWith;
@@ -56,33 +57,36 @@
 
 import static java.util.Objects.requireNonNull;
 
-/** Lowers CYCLE to a recursive UNION with a mark and an array of key tuples.
+/** Lowers SEARCH and CYCLE to a recursive UNION with generated columns.
  *
  * <p>Each row has its own path. The row closing a cycle is emitted, but is
  * filtered out before evaluating the next recursive step. Fresh syntax nodes
  * are used because the original query has already been validated. */
-final class CycleRewriter {
+final class RecursiveWithRewriter {
   private static final SqlParserPos POS = SqlParserPos.ZERO;
-  private static final String INPUT = "$CYCLE_INPUT";
+  private static final String INPUT = "$RECURSIVE_INPUT";
+  private static final String DEPTH = "$DEPTH";
 
   private final SqlValidatorImpl validator;
   private final SqlWithItem item;
-  private final SqlCycleClause cycle;
+  private final @Nullable SqlCycleClause cycle;
+  private final @Nullable SqlSearchClause search;
   private final SqlNameMatcher matcher;
 
-  private CycleRewriter(SqlValidatorImpl validator, SqlWithItem item) {
+  private RecursiveWithRewriter(SqlValidatorImpl validator, SqlWithItem item) {
     this.validator = validator;
     this.item = item;
-    this.cycle = requireNonNull(item.cycleClause);
+    this.cycle = item.cycleClause;
+    this.search = item.searchClause;
     this.matcher = validator.getCatalogReader().nameMatcher();
   }
 
   static SqlWithItem rewrite(SqlValidatorImpl validator, SqlValidatorScope 
scope,
       SqlWithItem item) {
-    return new CycleRewriter(validator, item).rewrite(scope);
+    return new RecursiveWithRewriter(validator, item).rewrite(scope);
   }
 
-  /** Replaces CYCLE with explicit mark and path columns in both UNION 
operands.
+  /** Replaces SEARCH and CYCLE with explicit generated columns in both UNION 
operands.
    *
    * <p>For {@code CYCLE k1, k2 SET mark TO cycleValue DEFAULT defaultValue
    * USING path}, the transformation is schematically:
@@ -110,25 +114,98 @@ static SqlWithItem rewrite(SqlValidatorImpl validator, 
SqlValidatorScope scope,
    * The added WHERE condition stops expanding rows already marked as cycles.
    * The recursive output keys are taken after the user's projection. A row
    * closing a cycle is therefore returned with its extended path, but cannot
-   * feed the next recursive step. The original UNION [ALL] is retained.
-   * The returned WITH item declares the two additional columns and no longer
-   * has a CYCLE clause. */
+   * feed the next recursive step.
+   *
+   * <p>For {@code SEARCH DEPTH FIRST BY k1, k2 SET searchOrder}, the
+   * transformation is schematically:
+   *
+   * <pre>{@code
+   * seed output:
+   *   original columns,
+   *   ARRAY[ROW(k1, k2)] AS searchOrder
+   * recursive branch:
+   *   SELECT original output columns,
+   *          append(previousOrder, ROW(k1, k2)) AS searchOrder
+   *   FROM (
+   *     SELECT original projection, previous.searchOrder AS previousOrder
+   *     FROM original sources
+   *     WHERE original condition
+   *   ) AS step
+   * }</pre>
+   *
+   * <p>The generated array contains the key tuples along the path, including
+   * the current row. Lexicographic ordering of these arrays places a parent
+   * before its descendants. For distinct sibling keys, a node's descendants
+   * precede the next sibling.
+   * The keys within each tuple follow the order of the BY list. Even a single
+   * BY column is wrapped in ROW, so the generated column is always an array
+   * of rows. The internal {@link SqlInternalOperators#RECURSIVE_PATH_APPEND}
+   * operator implements append.
+   *
+   * <p>For {@code SEARCH BREADTH FIRST BY k1, k2 SET searchOrder}, the
+   * transformation is schematically:
+   *
+   * <pre>{@code
+   * seed output:
+   *   original columns,
+   *   ROW(0, k1, k2) AS searchOrder
+   * recursive branch:
+   *   SELECT original output columns,
+   *          ROW(previousOrder.$DEPTH + 1, k1, k2) AS searchOrder
+   *   FROM (
+   *     SELECT original projection, previous.searchOrder AS previousOrder
+   *     FROM original sources
+   *     WHERE original condition
+   *   ) AS step
+   * }</pre>
+   *
+   * <p>Here {@code $DEPTH} denotes the first field of the generated row. It is
+   * an INTEGER starting at zero for every seed row and incremented at each
+   * recursive step. The remaining fields contain only the current row's keys,
+   * not the ancestors' keys. Ordering by this row therefore sorts by depth,
+   * then by the BY columns within each level, independently of parent order.
+   * Key field names are uniquified to avoid collisions with {@code $DEPTH}.
+   *
+   * <p>In both SEARCH transformations, the previous ordering value is carried
+   * through the inner SELECT alongside the user's original projection. The
+   * outer SELECT computes the new ordering value using the projected output
+   * keys, just as for CYCLE. The seed is also wrapped so that its output keys
+   * can be referenced when constructing the initial ordering value.
+   * SEARCH only computes a sort key: it neither adds an ORDER BY nor changes
+   * the physical evaluation order of recursion, and it does not detect cycles.
+   * The consuming query must use {@code ORDER BY searchOrder} to request the
+   * corresponding output order. Rows with equal ordering values have no
+   * guaranteed relative order.
+   *
+   * <p>The original UNION [ALL] is retained. If both clauses are present, they
+   * are lowered together so that the user's projection and recursive reference
+   * are only expanded once. The search column precedes the cycle mark and path
+   * columns, and the CYCLE filter still stops expansion of completed paths.
+   * The user's projection, including SELECT *, is expanded before generated
+   * columns are added; those columns are not visible in the user's recursive
+   * term. The returned WITH item declares all generated columns and no longer
+   * has SEARCH or CYCLE clauses. */
   private SqlWithItem rewrite(SqlValidatorScope scope) {
     final Reference reference = validateRecursiveQuery();
     final RelDataType rowType = 
validator.getNamespaceOrThrow(item).getRowType();
-    final List<RelDataTypeField> keys = validateKeys(rowType);
+    final List<RelDataTypeField> cycleKeys = cycle == null
+        ? ImmutableList.of() : validateKeys(rowType, cycle.columns, false);
+    final List<RelDataTypeField> searchKeys = search == null
+        ? ImmutableList.of() : validateKeys(rowType, search.columns, true);
     final List<String> names = rowType.getFieldNames();
     validateGeneratedNames(names);
-    final RelDataType markType = validateMarkType(scope);
+    final RelDataType markType = cycle == null ? null : 
validateMarkType(scope);
 
     final SqlNode query = prepareQuery(reference);
     final SqlCall union = (SqlCall) queryBody(query);
-    union.setOperand(0, rewriteSeed(union.operand(0), names, keys, markType));
-    union.setOperand(1, rewriteStep(union.operand(1), reference, names, keys, 
markType));
+    union.setOperand(0, rewriteSeed(union.operand(0), names, cycleKeys, 
searchKeys, markType));
+    union.setOperand(1,
+        rewriteStep(union.operand(1), reference, names, cycleKeys, searchKeys, 
markType));
 
     final List<SqlNode> outputNames = identifiers(names);
-    outputNames.add(copy(cycle.markColumn));
-    outputNames.add(copy(cycle.pathColumn));
+    for (SqlIdentifier generated : generatedColumns()) {
+      outputNames.add(copy(generated));
+    }
     return new SqlWithItem(item.getParserPosition(), item.name,
         new SqlNodeList(outputNames, POS), query, item.recursive);
   }
@@ -138,21 +215,27 @@ private Reference validateRecursiveQuery() {
     final SqlNode body = queryBody(item.query);
     if (body.getKind() != SqlKind.UNION
         || !(((SqlCall) body).operand(1) instanceof SqlSelect)) {
-      throw validator.newValidationError(cycle, 
RESOURCE.cycleRequiresRecursiveSelect());
+      throw invalidRecursiveQuery();
     }
     final SqlSelect step = ((SqlCall) body).operand(1);
     final List<SqlNode> references = new ArrayList<>();
     findDirectReferences(step.getFrom(), references);
     if (references.size() != 1 || recursiveReferenceCount() != 1) {
-      throw validator.newValidationError(cycle, 
RESOURCE.cycleRequiresRecursiveSelect());
+      throw invalidRecursiveQuery();
     }
     if (validator.isAggregate(step) || step.isDistinct() || 
!step.getWindowList().isEmpty()
         || SqlUtil.containsCall(step, call -> call.getKind() == SqlKind.OVER)) 
{
-      throw validator.newValidationError(cycle, 
RESOURCE.cycleRecursiveSelectNotSupported());
+      throw validator.newValidationError(search != null ? search : 
requireNonNull(cycle, "cycle"),
+          RESOURCE.recursiveClauseSelectNotSupported(search != null ? "SEARCH" 
: "CYCLE"));
     }
     return reference(references.get(0));
   }
 
+  private RuntimeException invalidRecursiveQuery() {
+    return validator.newValidationError(search != null ? search : 
requireNonNull(cycle, "cycle"),
+        RESOURCE.recursiveClauseRequiresRecursiveSelect(search != null ? 
"SEARCH" : "CYCLE"));
+  }
+
   /** Finds direct references on the non-null-generating sides of joins. */
   private void findDirectReferences(@Nullable SqlNode from, List<SqlNode> 
references) {
     if (isSelfReference(from)) {
@@ -196,14 +279,16 @@ private int recursiveReferenceCount() {
     return references.size();
   }
 
-  private List<RelDataTypeField> validateKeys(RelDataType rowType) {
+  private List<RelDataTypeField> validateKeys(RelDataType rowType,
+      SqlNodeList columns, boolean searchKeys) {
     final List<RelDataTypeField> keys = new ArrayList<>();
-    for (SqlNode node : cycle.columns) {
+    for (SqlNode node : columns) {
       final SqlIdentifier key = (SqlIdentifier) node;
       final RelDataTypeField field = matcher.field(rowType, key.getSimple());
       if (field == null) {
         throw validator.newValidationError(key,
-            RESOURCE.cycleColumnNotFound(key.getSimple(), 
item.name.getSimple()));
+            RESOURCE.recursiveClauseColumnNotFound(searchKeys ? "SEARCH" : 
"CYCLE",
+                key.getSimple(), item.name.getSimple()));
       }
       if (keys.contains(field)) {
         throw validator.newValidationError(key,
@@ -215,19 +300,32 @@ private List<RelDataTypeField> validateKeys(RelDataType 
rowType) {
   }
 
   private void validateGeneratedNames(List<String> names) {
-    if (matcher.matches(cycle.markColumn.getSimple(), 
cycle.pathColumn.getSimple())) {
-      throw validator.newValidationError(cycle.pathColumn,
-          RESOURCE.cycleColumnConflict(cycle.pathColumn.getSimple()));
-    }
-    for (SqlIdentifier generated : ImmutableList.of(cycle.markColumn, 
cycle.pathColumn)) {
-      if (matcher.indexOf(names, generated.getSimple()) >= 0) {
+    final Set<String> used = matcher.createSet();
+    used.addAll(names);
+    for (SqlIdentifier generated : generatedColumns()) {
+      if (!used.add(generated.getSimple())) {
         throw validator.newValidationError(generated,
-            RESOURCE.cycleColumnConflict(generated.getSimple()));
+            RESOURCE.recursiveClauseColumnConflict(
+                search != null && generated == search.orderColumn ? "SEARCH" : 
"CYCLE",
+                generated.getSimple()));
       }
     }
   }
 
+  private List<SqlIdentifier> generatedColumns() {
+    final List<SqlIdentifier> columns = new ArrayList<>();
+    if (search != null) {
+      columns.add(search.orderColumn);
+    }
+    if (cycle != null) {
+      columns.add(cycle.markColumn);
+      columns.add(cycle.pathColumn);
+    }
+    return columns;
+  }
+
   private RelDataType validateMarkType(SqlValidatorScope scope) {
+    final SqlCycleClause cycle = requireNonNull(this.cycle);
     if (!(cycle.markValue instanceof SqlLiteral)
         || !(cycle.defaultValue instanceof SqlLiteral)) {
       throw validator.newValidationError(cycle, 
RESOURCE.cycleInvalidMarkValues());
@@ -267,11 +365,17 @@ private Reference reference(SqlNode source) {
       aliases.addAll(
           SqlIdentifier.simpleNames(as.getOperandList().subList(2, 
as.operandCount())));
     }
-    final String mark =
-        SqlValidatorUtil.uniquify(cycle.markColumn.getSimple(), aliases, 
EXPR_SUGGESTER);
-    final String path =
-        SqlValidatorUtil.uniquify(cycle.pathColumn.getSimple(), aliases, 
EXPR_SUGGESTER);
-    return new Reference(source, qualified(alias, mark), qualified(alias, 
path));
+    final List<SqlIdentifier> columns = new ArrayList<>();
+    for (SqlIdentifier generated : generatedColumns()) {
+      columns.add(
+          qualified(alias,
+          SqlValidatorUtil.uniquify(generated.getSimple(), aliases, 
EXPR_SUGGESTER)));
+    }
+    return new Reference(source, columns);
+  }
+
+  private SqlIdentifier referenceColumn(Reference reference, SqlIdentifier 
column) {
+    return reference.columns.get(generatedColumns().indexOf(column));
   }
 
   /** Copies the query and adjusts joins and aliases before adding generated 
columns. */
@@ -296,8 +400,9 @@ private SqlNode prepareQuery(Reference reference) {
         }
         if (call == reference.source && call.operandCount() > 2) {
           final List<SqlNode> operands = new 
ArrayList<>(result.getOperandList());
-          operands.add(new SqlIdentifier(Util.last(reference.mark.names), 
POS));
-          operands.add(new SqlIdentifier(Util.last(reference.path.names), 
POS));
+          for (SqlIdentifier column : reference.columns) {
+            operands.add(new SqlIdentifier(Util.last(column.names), POS));
+          }
           return result.getOperator().createCall(result.getParserPosition(), 
operands);
         }
         return result;
@@ -316,38 +421,56 @@ private void makeJoinExplicit(SqlJoin original, SqlJoin 
copy) {
   }
 
   private SqlSelect rewriteSeed(SqlNode seed, List<String> names,
-      List<RelDataTypeField> keys, RelDataType markType) {
+      List<RelDataTypeField> cycleKeys, List<RelDataTypeField> searchKeys,
+      @Nullable RelDataType markType) {
     final List<SqlNode> columns = columns(names);
-    columns.add(cast(copy(cycle.defaultValue), markType));
-    columns.add(SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR.createCall(POS, 
key(keys)));
+    if (search != null) {
+      columns.add(searchOrder(searchKeys, true));
+    }
+    if (cycle != null) {
+      columns.add(cast(copy(cycle.defaultValue), requireNonNull(markType, 
"markType")));
+      columns.add(SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR.createCall(POS, 
key(cycleKeys)));
+    }
     return select(columns, alias(seed, names));
   }
 
   private SqlSelect rewriteStep(SqlSelect step, Reference reference, 
List<String> names,
-      List<RelDataTypeField> keys, RelDataType markType) {
-    excludeCompletedPaths(step, reference, markType);
+      List<RelDataTypeField> cycleKeys, List<RelDataTypeField> searchKeys,
+      @Nullable RelDataType markType) {
     final List<String> inputNames = new ArrayList<>(names);
-    inputNames.add(cycle.pathColumn.getSimple());
     final List<SqlNode> columns = columns(names);
-    columns.add(cycleMark(keys, markType));
-    columns.add(
-        SqlInternalOperators.CYCLE_PATH_APPEND.createCall(POS, previousPath(), 
key(keys)));
+    final List<SqlNode> stepColumns = new ArrayList<>(step.getSelectList());
+    if (search != null) {
+      inputNames.add(search.orderColumn.getSimple());
+      stepColumns.add(referenceColumn(reference, search.orderColumn));
+      columns.add(searchOrder(searchKeys, false));
+    }
+    if (cycle != null) {
+      excludeCompletedPaths(step, reference, requireNonNull(markType, 
"markType"));
+      inputNames.add(cycle.pathColumn.getSimple());
+      stepColumns.add(referenceColumn(reference, cycle.pathColumn));
+      columns.add(cycleMark(cycleKeys, requireNonNull(markType, "markType")));
+      columns.add(
+          SqlInternalOperators.RECURSIVE_PATH_APPEND.createCall(POS,
+              previousPath(), key(cycleKeys)));
+    }
+    step.setSelectList(new SqlNodeList(stepColumns, POS));
     return select(columns, alias(step, inputNames));
   }
 
-  /** Filters closed paths and carries the previous path through the user's 
projection. */
+  /** Filters closed paths before evaluating the user's projection. */
   private void excludeCompletedPaths(SqlSelect step, Reference reference, 
RelDataType markType) {
+    final SqlCycleClause cycle = requireNonNull(this.cycle);
     final SqlNode mark = cast(copy(cycle.markValue), markType);
     final SqlNode live =
-        SqlStdOperatorTable.NOT_EQUALS.createCall(POS, reference.mark, mark);
+        SqlStdOperatorTable.NOT_EQUALS.createCall(POS,
+            referenceColumn(reference, cycle.markColumn), mark);
     step.setWhere(step.getWhere() == null ? live
         : SqlStdOperatorTable.AND.createCall(POS, step.getWhere(), live));
-    final List<SqlNode> columns = new ArrayList<>(step.getSelectList());
-    columns.add(reference.path);
-    step.setSelectList(new SqlNodeList(columns, POS));
   }
 
   private SqlNode cycleMark(List<RelDataTypeField> keys, RelDataType markType) 
{
+    final SqlCycleClause cycle = requireNonNull(this.cycle);
     final SqlNode contains =
         SqlInternalOperators.CYCLE_PATH_CONTAINS.createCall(POS, 
previousPath(), key(keys));
     return new SqlCase(POS, null, SqlNodeList.of(contains),
@@ -356,7 +479,31 @@ private SqlNode cycleMark(List<RelDataTypeField> keys, 
RelDataType markType) {
   }
 
   private SqlIdentifier previousPath() {
-    return qualified(INPUT, cycle.pathColumn.getSimple());
+    return qualified(INPUT, requireNonNull(cycle, 
"cycle").pathColumn.getSimple());
+  }
+
+  private SqlNode searchOrder(List<RelDataTypeField> keys, boolean seed) {
+    final SqlSearchClause search = requireNonNull(this.search);
+    final SqlIdentifier previous = qualified(INPUT, 
search.orderColumn.getSimple());
+    if (search.getSearchMode() == SqlSearchClause.SearchMode.DEPTH) {
+      return seed
+          ? SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR.createCall(POS, 
key(keys))
+          : SqlInternalOperators.RECURSIVE_PATH_APPEND.createCall(POS, 
previous, key(keys));
+    }
+    // The private depth field cannot collide with a user's BY column name.
+    final List<String> fieldNames = new ArrayList<>();
+    final Set<String> usedNames = matcher.createSet();
+    final List<SqlNode> values = new ArrayList<>();
+    fieldNames.add(DEPTH);
+    usedNames.add(DEPTH);
+    values.add(seed ? SqlLiteral.createExactNumeric("0", POS)
+        : SqlStdOperatorTable.PLUS.createCall(POS, previous.plus(DEPTH, POS),
+            SqlLiteral.createExactNumeric("1", POS)));
+    for (RelDataTypeField field : keys) {
+      fieldNames.add(SqlValidatorUtil.uniquify(field.getName(), usedNames, 
EXPR_SUGGESTER));
+      values.add(cast(qualified(INPUT, field.getName()), field.getType()));
+    }
+    return new SqlRowOperator("ROW", fieldNames).createCall(POS, values);
   }
 
   private static SqlNode queryBody(SqlNode query) {
@@ -411,13 +558,11 @@ private static SqlNode copy(SqlNode node) {
   /** Original recursive table reference and its qualified generated columns. 
*/
   private static class Reference {
     final SqlNode source;
-    final SqlIdentifier mark;
-    final SqlIdentifier path;
+    final List<SqlIdentifier> columns;
 
-    Reference(SqlNode source, SqlIdentifier mark, SqlIdentifier path) {
+    Reference(SqlNode source, List<SqlIdentifier> columns) {
       this.source = source;
-      this.mark = mark;
-      this.path = path;
+      this.columns = columns;
     }
   }
 
diff --git 
a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java 
b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
index b514acc61d..5161ee8c1e 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
@@ -81,6 +81,7 @@
 import org.apache.calcite.sql.SqlPipeQuery;
 import org.apache.calcite.sql.SqlPivot;
 import org.apache.calcite.sql.SqlSampleSpec;
+import org.apache.calcite.sql.SqlSearchClause;
 import org.apache.calcite.sql.SqlSelect;
 import org.apache.calcite.sql.SqlSelectKeyword;
 import org.apache.calcite.sql.SqlSnapshot;
@@ -3884,17 +3885,21 @@ private void registerWith(
     SqlValidatorScope scope = parentScope;
     for (int i = 0; i < with.withList.size(); i++) {
       SqlWithItem withItem = (SqlWithItem) with.withList.get(i);
+      final SqlSearchClause searchClause = withItem.searchClause;
+      if (searchClause != null && !withItem.recursive.booleanValue()) {
+        throw newValidationError(searchClause, 
RESOURCE.recursiveClauseRequiresRecursive("SEARCH"));
+      }
       final SqlCycleClause cycleClause = withItem.cycleClause;
       if (cycleClause != null && !withItem.recursive.booleanValue()) {
-        throw newValidationError(cycleClause, 
RESOURCE.cycleRequiresRecursive());
+        throw newValidationError(cycleClause, 
RESOURCE.recursiveClauseRequiresRecursive("CYCLE"));
       }
       SqlValidatorScope withScope =
           registerWithItem(scope, with, withItem, enclosingNode, alias, 
forceNullable);
-      if (withItem.cycleClause != null) {
+      if (cycleClause != null || searchClause != null) {
         // Validate and expand the user's projection before adding the 
generated
-        // columns. In particular, SELECT * must not pick up the path or mark.
+        // columns. In particular, SELECT * must not pick up generated columns.
         validateWithItem(withItem);
-        withItem = CycleRewriter.rewrite(this, scope, withItem);
+        withItem = RecursiveWithRewriter.rewrite(this, scope, withItem);
         with.withList.set(i, withItem);
         withScope = registerWithItem(scope, with, withItem, enclosingNode, 
alias, forceNullable);
       }
diff --git 
a/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties 
b/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
index 7e5fff8557..09f1053fb8 100644
--- 
a/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
+++ 
b/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
@@ -75,11 +75,11 @@ IncompatibleCharset=Cannot apply operation ''{0}'' to 
strings with different cha
 InvalidOrderByPos=ORDER BY is only allowed on top-level SELECT
 RecursiveWithMustHaveUnionSetOp=A recursive query only supports UNION [ALL] 
operator
 RecursiveWithMustHaveTwoChildUnionSetOp=A recursive query only supports binary 
UNION [ALL] operator
-CycleRequiresRecursive=CYCLE requires WITH RECURSIVE
-CycleRequiresRecursiveSelect=CYCLE requires a UNION [ALL] with a recursive 
SELECT containing exactly one direct reference to its WITH item
-CycleRecursiveSelectNotSupported=CYCLE is not supported with aggregation, 
DISTINCT, or window functions in the recursive SELECT
-CycleColumnNotFound=CYCLE column ''{0}'' is not a column of WITH item ''{1}''
-CycleColumnConflict=CYCLE generated column ''{0}'' conflicts with another 
column
+RecursiveClauseRequiresRecursive={0} requires WITH RECURSIVE
+RecursiveClauseRequiresRecursiveSelect={0} requires a UNION [ALL] with a 
recursive SELECT containing exactly one direct reference to its WITH item
+RecursiveClauseSelectNotSupported={0} is not supported with aggregation, 
DISTINCT, or window functions in the recursive SELECT
+RecursiveClauseColumnNotFound={0} column ''{1}'' is not a column of WITH item 
''{2}''
+RecursiveClauseColumnConflict={0} generated column ''{1}'' conflicts with 
another column
 CycleInvalidMarkValues=CYCLE mark and default must be distinct, non-null 
Boolean or compatible single-character string literals
 UnknownIdentifier=Unknown identifier ''{0}''
 UnknownField=Unknown field ''{0}''
diff --git a/core/src/test/java/org/apache/calcite/sql/SqlCallOperandsTest.java 
b/core/src/test/java/org/apache/calcite/sql/SqlCallOperandsTest.java
index f2a36927e2..fb47b5ffaf 100644
--- a/core/src/test/java/org/apache/calcite/sql/SqlCallOperandsTest.java
+++ b/core/src/test/java/org/apache/calcite/sql/SqlCallOperandsTest.java
@@ -26,10 +26,13 @@
 import java.util.Arrays;
 import java.util.List;
 
+import static org.hamcrest.CoreMatchers.nullValue;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.sameInstance;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 /**
  * Tests for SqlCall operands' order and size match with set.
@@ -37,6 +40,66 @@
  *
  */
 public class SqlCallOperandsTest {
+  @Test void testSqlWithItemSearchAndCycleOperands() throws SqlParseException {
+    final String sql =
+        "WITH RECURSIVE t(n) AS (VALUES (1) UNION ALL SELECT n + 1 FROM t 
WHERE n < 3)\n"
+            + "SEARCH DEPTH FIRST BY n SET seq CYCLE n SET c USING p\n"
+            + "SELECT * FROM t";
+    final SqlWith with = (SqlWith) SqlParser.create(sql).parseQuery();
+    final SqlWithItem item = (SqlWithItem) with.withList.get(0);
+    assertThat(item.getOperandList(), hasSize(6));
+    assertThat(item.operand(4), sameInstance(item.searchClause));
+    assertThat(item.operand(5), sameInstance(item.cycleClause));
+
+    // Cloning recreates the call from its operand list.
+    final SqlWithItem copy = (SqlWithItem) item.clone(SqlParserPos.ZERO);
+    assertThat(copy.searchClause, sameInstance(item.searchClause));
+    assertThat(copy.cycleClause, sameInstance(item.cycleClause));
+    copy.setOperand(4, null);
+    assertThat(copy.searchClause, nullValue());
+    assertThat(copy.cycleClause, sameInstance(item.cycleClause));
+    copy.setOperand(5, null);
+    assertThat(copy.cycleClause, nullValue());
+    copy.setOperand(4, item.searchClause);
+    copy.setOperand(5, item.cycleClause);
+    assertThat(copy.getOperandList(), equalTo(item.getOperandList()));
+  }
+
+  @Test void testSqlWithItemCreateCall() throws SqlParseException {
+    final String sql =
+        "WITH RECURSIVE t(n) AS (VALUES (1) UNION ALL SELECT n + 1 FROM t 
WHERE n < 3)\n"
+            + "SEARCH DEPTH FIRST BY n SET seq CYCLE n SET c USING p\n"
+            + "SELECT * FROM t";
+    final SqlWith with = (SqlWith) SqlParser.create(sql).parseQuery();
+    final SqlWithItem item = (SqlWithItem) with.withList.get(0);
+    final SqlOperator operator = item.getOperator();
+    final SqlWithItem withoutClauses =
+        (SqlWithItem) operator.createCall(SqlParserPos.ZERO,
+            item.name, item.columnList, item.query, item.recursive);
+    assertThat(withoutClauses.searchClause, nullValue());
+    assertThat(withoutClauses.cycleClause, nullValue());
+
+    // Six operands preserve the clause positions even when either clause is 
absent.
+    for (SqlSearchClause search : Arrays.asList(null, item.searchClause)) {
+      for (SqlCycleClause cycle : Arrays.asList(null, item.cycleClause)) {
+        final SqlWithItem copy =
+            (SqlWithItem) operator.createCall(SqlParserPos.ZERO,
+                item.name, item.columnList, item.query, item.recursive, 
search, cycle);
+        assertThat(copy.searchClause, sameInstance(search));
+        assertThat(copy.cycleClause, sameInstance(cycle));
+      }
+    }
+
+    // Five operands are ambiguous: the final operand could be SEARCH or CYCLE.
+    for (SqlNode clause : Arrays.asList(null, item.searchClause, 
item.cycleClause)) {
+      final IllegalArgumentException exception =
+          assertThrows(IllegalArgumentException.class,
+              () -> operator.createCall(SqlParserPos.ZERO,
+                  item.name, item.columnList, item.query, item.recursive, 
clause));
+      assertThat(exception.getMessage(), equalTo("Expected 4 or 6 operands, 
got 5"));
+    }
+  }
+
   @Test void testSqlBasicCallSetOperandList() {
     final SqlLiteral one =
         SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO);
diff --git a/core/src/test/java/org/apache/calcite/test/RecursiveCteTest.java 
b/core/src/test/java/org/apache/calcite/test/RecursiveCteTest.java
index 1ace435df9..b776c1fdb9 100644
--- a/core/src/test/java/org/apache/calcite/test/RecursiveCteTest.java
+++ b/core/src/test/java/org/apache/calcite/test/RecursiveCteTest.java
@@ -23,7 +23,11 @@
 import org.apache.calcite.sql.SqlIdentifier;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.sql.SqlLiteral;
+import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.SqlNodeList;
+import org.apache.calcite.sql.SqlOrderBy;
+import org.apache.calcite.sql.SqlSearchClause;
+import org.apache.calcite.sql.SqlSearchClause.SearchMode;
 import org.apache.calcite.sql.SqlSelect;
 import org.apache.calcite.sql.SqlWith;
 import org.apache.calcite.sql.SqlWithItem;
@@ -31,6 +35,7 @@
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.parser.SqlParseException;
 import org.apache.calcite.sql.parser.SqlParser;
+import org.apache.calcite.sql.type.SqlTypeName;
 
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.Timeout;
@@ -38,6 +43,8 @@
 import org.junit.jupiter.params.provider.CsvSource;
 import org.junit.jupiter.params.provider.ValueSource;
 
+import java.util.regex.Pattern;
+
 import static org.apache.calcite.test.Matchers.isLinux;
 
 import static org.hamcrest.CoreMatchers.containsString;
@@ -48,7 +55,7 @@
 import static java.util.Objects.requireNonNull;
 
 /** Examples of recursive CTE parsing, validation and execution, including the
- * SQL-standard CYCLE clause. */
+ * SQL-standard SEARCH and CYCLE clauses. */
 @Timeout(30)
 class RecursiveCteTest {
   private static final String WITH_NUMBERS = "WITH RECURSIVE t(n) AS (\n"
@@ -59,6 +66,12 @@ class RecursiveCteTest {
 
   private static final String NUMBERS = WITH_NUMBERS + "SELECT * FROM t";
 
+  private static final String WITH_TREE = "WITH RECURSIVE edges(src, dst) AS 
(\n"
+      + "  VALUES (0, 2), (0, 1), (1, 4), (2, 3)),\n"
+      + "walk(node) AS (VALUES (0)\n"
+      + "  UNION ALL\n"
+      + "  SELECT e.dst FROM walk AS w JOIN edges AS e ON e.src = w.node)\n";
+
   /** The self-reference is an identifier in the parse tree, not a Java object
    * reference back to the WITH item. Name resolution happens during 
validation.
    *
@@ -82,8 +95,8 @@ class RecursiveCteTest {
     final SqlNodeList columnList = requireNonNull(item.columnList);
     assertThat(columnList, hasSize(1));
     assertThat(((SqlIdentifier) columnList.get(0)).getSimple(), is("N"));
-    // CYCLE is the optional fifth operand of a WITH item.
-    assertThat(item.getOperandList(), hasSize(5));
+    // SEARCH and CYCLE are the optional fifth and sixth operands of a WITH 
item.
+    assertThat(item.getOperandList(), hasSize(6));
     final SqlCall union = (SqlCall) item.query;
     assertThat(union.getOperator(), is(SqlStdOperatorTable.UNION_ALL));
     assertThat(union.operand(0).getKind(), is(SqlKind.VALUES));
@@ -105,6 +118,264 @@ class RecursiveCteTest {
     assertThat(((SqlWithItem) with.withList.get(1)).recursive.booleanValue(), 
is(true));
   }
 
+  /** SEARCH follows AS (query); parsing and unparsing preserve its mode and 
keys. */
+  @ParameterizedTest
+  @CsvSource(delimiter = '|', value = {
+      "DEPTH|n", "BREADTH|n", "DEPTH|n, depth", "BREADTH|n, depth"
+  })
+  void testSearchClause(String mode, String keys) throws SqlParseException {
+    final String sql = "WITH RECURSIVE t(n, depth) AS (VALUES (1, 0)\n"
+        + "UNION ALL SELECT n + 1, depth + 1 FROM t WHERE n < 3)\n"
+        + "SEARCH " + mode + " FIRST BY " + keys + " SET seq\n"
+        + "SELECT n FROM t ORDER BY seq";
+    final SqlNode parsed = SqlParser.create(sql).parseQuery();
+    final SqlWith with = (SqlWith) ((SqlOrderBy) parsed).query;
+    final SqlSearchClause search =
+        requireNonNull(((SqlWithItem) with.withList.get(0)).searchClause);
+    assertThat(search.getKind(), is(SqlKind.SEARCH_CLAUSE));
+    assertThat(search.mode.getTypeName(), is(SqlTypeName.SYMBOL));
+    assertThat(search.getSearchMode(), is(SearchMode.valueOf(mode)));
+    assertThat(search.orderColumn.getSimple(), is("SEQ"));
+    assertThat(search.columns, hasSize(keys.equals("n") ? 1 : 2));
+    assertThat(search.getParserPosition().getLineNum(), is(3));
+    final String unparsed = 
parsed.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
+    final String quotedKeys = keys.equals("n") ? "\"N\"" : "\"N\", \"DEPTH\"";
+    assertThat(Pattern.compile("\\s+").matcher(unparsed).replaceAll(" "),
+        containsString("SEARCH " + mode + " FIRST BY " + quotedKeys + " SET 
\"SEQ\""));
+    final SqlNode roundTrip = SqlParser.create(unparsed).parseQuery();
+    assertThat(roundTrip.toSqlString(CalciteSqlDialect.DEFAULT).getSql(), 
is(unparsed));
+
+    final SqlSearchClause copy = (SqlSearchClause) 
search.clone(search.getParserPosition());
+    assertThat(copy.getSearchMode(), is(search.getSearchMode()));
+    final SearchMode otherMode = search.getSearchMode() == SearchMode.DEPTH
+        ? SearchMode.BREADTH : SearchMode.DEPTH;
+    copy.setOperand(0, otherMode.symbol(search.getParserPosition()));
+    assertThat(copy.getSearchMode(), is(otherMode));
+    assertThat(search.getSearchMode(), is(SearchMode.valueOf(mode)));
+  }
+
+  /** SEARCH creates a sort key; ORDER BY requests the corresponding row 
order. */
+  @Test void testSearchDepthFirst() {
+    CalciteAssert.that()
+        .query(WITH_TREE + "SEARCH DEPTH FIRST BY node SET seq\n"
+            + "SELECT node FROM walk ORDER BY seq")
+        .returnsOrdered("NODE=0", "NODE=1", "NODE=4", "NODE=2", "NODE=3");
+  }
+
+  /** Within a level, BY keys take precedence over the parents' order. */
+  @Test void testSearchBreadthFirst() {
+    CalciteAssert.that()
+        .query(WITH_TREE + "SEARCH BREADTH FIRST BY node SET seq\n"
+            + "SELECT node FROM walk ORDER BY seq")
+        .returnsOrdered("NODE=0", "NODE=1", "NODE=2", "NODE=3", "NODE=4");
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"DEPTH", "BREADTH"})
+  void testSearchCompositeKey(String mode) {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE t(n, k, depth) AS (VALUES (0, 0, 0)\n"
+            + "UNION ALL SELECT v.n, v.k, t.depth + 1\n"
+            + "FROM t CROSS JOIN (VALUES (1, 2), (2, 1), (1, 1)) AS v(n, k)\n"
+            + "WHERE t.depth < 1)\n"
+            + "SEARCH " + mode + " FIRST BY k, n SET seq\n"
+            + "SELECT n, k FROM t ORDER BY seq")
+        .returnsOrdered("N=0; K=0", "N=1; K=1", "N=2; K=1", "N=1; K=2");
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"DEPTH", "BREADTH"})
+  void testSearchFollowingWithItem(String mode) {
+    CalciteAssert.that()
+        .query(WITH_NUMBERS + "SEARCH " + mode + " FIRST BY n SET seq,\n"
+            + "u AS (SELECT * FROM t) SELECT n FROM u ORDER BY seq")
+        .returnsOrdered("N=1", "N=2", "N=3");
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"DEPTH", "BREADTH"})
+  void testSearchQuotedNames(String mode) {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE \"Walk\"(\"Node\") AS (VALUES (1)\n"
+            + "UNION ALL SELECT \"Node\" + 1 FROM \"Walk\" WHERE \"Node\" < 
3)\n"
+            + "SEARCH " + mode + " FIRST BY \"Node\" SET \"Sequence\"\n"
+            + "SELECT \"Node\" FROM \"Walk\" ORDER BY \"Sequence\"")
+        .returnsOrdered("Node=1", "Node=2", "Node=3");
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"DEPTH", "BREADTH"})
+  void testSearchEmptySeed(String mode) {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE t(n) AS (SELECT n FROM (VALUES (1)) AS v(n) 
WHERE FALSE\n"
+            + "UNION ALL SELECT n + 1 FROM t WHERE n < 3)\n"
+            + "SEARCH " + mode + " FIRST BY n SET seq\n"
+            + "SELECT * FROM t ORDER BY seq")
+        .returnsCount(0);
+  }
+
+  /** SEARCH precedes CYCLE, which stops expansion of the repeated node. */
+  @ParameterizedTest
+  @ValueSource(strings = {"DEPTH", "BREADTH"})
+  void testSearchWithCycle(String mode) {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE t(n, depth) AS (VALUES (1, 0)\n"
+            + "UNION ALL SELECT MOD(n + 1, 3), depth + 1 FROM t WHERE depth < 
5)\n"
+            + "SEARCH " + mode + " FIRST BY n SET seq\n"
+            + "CYCLE n SET c TO 'Y' DEFAULT 'N' USING p\n"
+            + "SELECT n, c, CARDINALITY(p) AS path_length FROM t ORDER BY seq")
+        .returnsOrdered("N=1; C=N; PATH_LENGTH=1", "N=2; C=N; PATH_LENGTH=2",
+            "N=0; C=N; PATH_LENGTH=3", "N=1; C=Y; PATH_LENGTH=4");
+  }
+
+  @ParameterizedTest
+  @CsvSource({"DEPTH, UNION ALL", "BREADTH, UNION ALL",
+      "DEPTH, UNION", "BREADTH, UNION"})
+  void testSearchMultipleRoots(String mode, String union) {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE t(n) AS (VALUES (2), (1)\n"
+            + union + " SELECT n + 2 FROM t WHERE n < 3)\n"
+            + "SEARCH " + mode + " FIRST BY n SET seq\n"
+            + "SELECT n FROM t ORDER BY seq")
+        .returnsOrdered(mode.equals("DEPTH")
+            ? new String[]{"N=1", "N=3", "N=2", "N=4"}
+            : new String[]{"N=1", "N=2", "N=3", "N=4"});
+  }
+
+  /** NULLS FIRST/LAST applies to seq itself, which is non-null even when a
+   * BY key is null. Descending order reverses the comparison of nested keys. 
*/
+  @ParameterizedTest
+  @CsvSource({
+      "DEPTH, ASC NULLS FIRST", "DEPTH, ASC NULLS LAST",
+      "DEPTH, DESC NULLS FIRST", "DEPTH, DESC NULLS LAST",
+      "BREADTH, ASC NULLS FIRST", "BREADTH, ASC NULLS LAST",
+      "BREADTH, DESC NULLS FIRST", "BREADTH, DESC NULLS LAST"
+  })
+  void testSearchNullKey(String mode, String order) {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE t(n, depth) AS (VALUES (0, 0)\n"
+            + "UNION ALL SELECT v.n, t.depth + 1\n"
+            + "FROM t CROSS JOIN (VALUES (CAST(NULL AS INTEGER)), (2), (1)) AS 
v(n)\n"
+            + "WHERE t.depth < 1)\n"
+            + "SEARCH " + mode + " FIRST BY n SET seq\n"
+            + "SELECT n FROM t ORDER BY seq " + order)
+        .returnsOrdered(order.startsWith("DESC")
+            ? new String[]{"N=null", "N=2", "N=1", "N=0"}
+            : new String[]{"N=0", "N=1", "N=2", "N=null"});
+  }
+
+  @ParameterizedTest
+  @CsvSource({"DEPTH, false", "BREADTH, false", "DEPTH, true", "BREADTH, 
true"})
+  void testSearchMultipleSortKeys(String mode, boolean limit) {
+    CalciteAssert.that()
+        .query(WITH_TREE + "SEARCH " + mode + " FIRST BY node SET seq\n"
+            + "SELECT node FROM walk ORDER BY seq DESC, node"
+            + (limit ? " FETCH NEXT 5 ROWS ONLY" : ""))
+        .returnsOrdered(mode.equals("DEPTH")
+            ? new String[]{"NODE=3", "NODE=2", "NODE=4", "NODE=1", "NODE=0"}
+            : new String[]{"NODE=4", "NODE=3", "NODE=2", "NODE=1", "NODE=0"});
+  }
+
+  @ParameterizedTest
+  @CsvSource({"false, *", "true, *", "false, t.*", "true, t.*"})
+  void testSearchStarInRecursiveTerm(boolean identifierExpansion, String 
projection) {
+    SqlValidatorTestCase.FIXTURE
+        .withValidatorIdentifierExpansion(identifierExpansion)
+        .withSql("WITH RECURSIVE t(n) AS (VALUES (1)\n"
+            + "UNION ALL SELECT " + projection + " FROM t WHERE n < 0)\n"
+            + "SEARCH DEPTH FIRST BY n SET seq SELECT * FROM t")
+        .type("RecordType(INTEGER NOT NULL N, "
+            + "RecordType(INTEGER NOT NULL N) NOT NULL ARRAY NOT NULL SEQ) NOT 
NULL");
+  }
+
+  @Test void testSearchBreadthFirstRowType() {
+    SqlValidatorTestCase.FIXTURE.withSql(WITH_NUMBERS
+        + "SEARCH BREADTH FIRST BY n SET seq SELECT * FROM t")
+        .type("RecordType(INTEGER NOT NULL N, "
+            + "RecordType(INTEGER NOT NULL $DEPTH, INTEGER NOT NULL N) NOT 
NULL SEQ) NOT NULL");
+  }
+
+  /** A user key named $DEPTH must remain separate from the generated depth 
field. */
+  @Test void testSearchBreadthFirstDepthNameCollision() {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE t(\"$DEPTH\") AS (VALUES (100)\n"
+            + "UNION ALL SELECT t.\"$DEPTH\" - v.n\n"
+            + "FROM t CROSS JOIN (VALUES (10), (20)) AS v(n)\n"
+            + "WHERE t.\"$DEPTH\" > 80)\n"
+            + "SEARCH BREADTH FIRST BY \"$DEPTH\" SET seq\n"
+            + "SELECT \"$DEPTH\", seq FROM t ORDER BY seq")
+        .returnsOrdered("$DEPTH=100; SEQ={0, 100}",
+            "$DEPTH=80; SEQ={1, 80}", "$DEPTH=90; SEQ={1, 90}",
+            "$DEPTH=70; SEQ={2, 70}", "$DEPTH=80; SEQ={2, 80}");
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"DEPTH", "BREADTH"})
+  void testSearchColumnAliases(String mode) {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE t(n) AS (VALUES (1)\n"
+            + "UNION ALL SELECT w.seq + 1 FROM t AS w(seq) WHERE w.seq < 3)\n"
+            + "SEARCH " + mode + " FIRST BY n SET seq SELECT n FROM t ORDER BY 
seq")
+        .returnsOrdered("N=1", "N=2", "N=3");
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"DEPTH", "BREADTH"})
+  void testSearchInferredColumnNames(String mode) {
+    CalciteAssert.that()
+        .query("WITH RECURSIVE t AS (SELECT 1 AS n\n"
+            + "UNION ALL SELECT n + 1 FROM t WHERE n < 3)\n"
+            + "SEARCH " + mode + " FIRST BY n SET seq SELECT n FROM t ORDER BY 
seq")
+        .returnsOrdered("N=1", "N=2", "N=3");
+  }
+
+  @ParameterizedTest
+  @CsvSource(delimiter = '|', value = {
+      "SEARCH DEPTH FIRST BY ^missing^ SET seq|SEARCH column 'MISSING' is not 
a column of WITH item 'T'",
+      "SEARCH BREADTH FIRST BY n, ^n^ SET seq|Duplicate name 'N' in column 
list",
+      "SEARCH DEPTH FIRST BY n SET ^n^|SEARCH generated column 'N' conflicts 
with another column",
+      "SEARCH DEPTH FIRST BY n SET seq CYCLE n SET ^seq^ USING p|CYCLE 
generated column 'SEQ' conflicts with another column",
+      "SEARCH BREADTH FIRST BY n SET seq CYCLE n SET c USING ^seq^|CYCLE 
generated column 'SEQ' conflicts with another column"
+  })
+  void testSearchInvalidColumns(String clause, String error) {
+    SqlValidatorTestCase.FIXTURE.withSql(WITH_NUMBERS + clause + " SELECT * 
FROM t")
+        .fails(error);
+  }
+
+  @Test void testSearchRequiresRecursive() {
+    SqlValidatorTestCase.FIXTURE.withSql("WITH t(n) AS (VALUES (1))\n"
+        + "^SEARCH DEPTH FIRST BY n SET seq^ SELECT * FROM t")
+        .fails("SEARCH requires WITH RECURSIVE");
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"SELECT 2", "SELECT a.n FROM t a JOIN t b ON a.n = 
b.n",
+      "SELECT a.n FROM (VALUES (1)) v(n) LEFT JOIN t a ON a.n = v.n",
+      "SELECT a.n FROM t a WHERE EXISTS (SELECT 1 FROM t b WHERE b.n = a.n)"})
+  void testSearchInvalidRecursiveReference(String step) {
+    SqlValidatorTestCase.FIXTURE.withSql("WITH RECURSIVE t(n) AS (VALUES (1)\n"
+        + "UNION ALL " + step + ") ^SEARCH DEPTH FIRST BY n SET seq^ SELECT * 
FROM t")
+        .fails("SEARCH requires a UNION \\[ALL\\] with a recursive SELECT 
containing"
+            + " exactly one direct reference to its WITH item");
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings =
+      {"SELECT DISTINCT n FROM t", "SELECT MAX(n) FROM t", "SELECT SUM(n) OVER 
() FROM t"})
+  void testSearchInvalidRecursiveSelect(String step) {
+    SqlValidatorTestCase.FIXTURE.withSql("WITH RECURSIVE t(n) AS (VALUES (1)\n"
+        + "UNION ALL " + step + ") ^SEARCH BREADTH FIRST BY n SET seq^ SELECT 
* FROM t")
+        .fails("SEARCH is not supported with aggregation, DISTINCT, or window 
functions"
+            + " in the recursive SELECT");
+  }
+
+  @Test void testSearchOrderNotVisibleInRecursiveTerm() {
+    SqlValidatorTestCase.FIXTURE.withSql("WITH RECURSIVE t(n) AS (VALUES (1)\n"
+        + "UNION ALL SELECT n FROM t WHERE ^seq^ IS NOT NULL)\n"
+        + "SEARCH DEPTH FIRST BY n SET seq SELECT * FROM t")
+        .fails("Column 'SEQ' not found in any table");
+  }
+
   /** CYCLE follows AS (query) and belongs to that WITH item. */
   @ParameterizedTest
   @ValueSource(strings = {
@@ -409,7 +680,7 @@ void testCycleBooleanMarks(boolean mark) {
     final String plan = RelOptUtil.toString(rel);
     assertThat(plan, containsString("LogicalRepeatUnion(all=[true])"));
     assertThat(plan, containsString("$CYCLE_PATH_CONTAINS"));
-    assertThat(plan, containsString("$CYCLE_PATH_APPEND"));
+    assertThat(plan, containsString("$RECURSIVE_PATH_APPEND"));
   }
 
   @ParameterizedTest
diff --git a/core/src/test/resources/sql/recursive_queries.iq 
b/core/src/test/resources/sql/recursive_queries.iq
index 25a5a9508c..98fb490896 100644
--- a/core/src/test/resources/sql/recursive_queries.iq
+++ b/core/src/test/resources/sql/recursive_queries.iq
@@ -591,4 +591,318 @@ SELECT * FROM t;
 CYCLE mark and default must be distinct, non-null Boolean or compatible 
single-character string literals
 !error
 
+# SEARCH creates a sort key. The outer ORDER BY requests depth-first output.
+# A child is visited before the next sibling, even when its key is larger.
+WITH RECURSIVE edges(src, dst) AS (
+    VALUES (0, 2), (0, 1), (1, 4), (2, 3)
+),
+walk(node) AS (
+    VALUES (0)
+    UNION ALL
+    SELECT e.dst FROM walk w JOIN edges e ON e.src = w.node
+)
+SEARCH DEPTH FIRST BY node SET seq
+SELECT * FROM walk ORDER BY seq;
++------+-----------------+
+| NODE | SEQ             |
++------+-----------------+
+|    0 | [{0}]           |
+|    1 | [{0}, {1}]      |
+|    4 | [{0}, {1}, {4}] |
+|    2 | [{0}, {2}]      |
+|    3 | [{0}, {2}, {3}] |
++------+-----------------+
+(5 rows)
+
+!ok
+
+# Breadth-first ordering uses depth followed by the current key, not the
+# parent's position. At depth 2, node 3 therefore precedes node 4.
+WITH RECURSIVE edges(src, dst) AS (
+    VALUES (0, 2), (0, 1), (1, 4), (2, 3)
+),
+walk(node) AS (
+    VALUES (0)
+    UNION ALL
+    SELECT e.dst FROM walk w JOIN edges e ON e.src = w.node
+)
+SEARCH BREADTH FIRST BY node SET seq
+SELECT * FROM walk ORDER BY seq;
++------+--------+
+| NODE | SEQ    |
++------+--------+
+|    0 | {0, 0} |
+|    1 | {1, 1} |
+|    2 | {1, 2} |
+|    3 | {2, 3} |
+|    4 | {2, 4} |
++------+--------+
+(5 rows)
+
+!ok
+
+# Composite BY keys are compared in the specified order.
+WITH RECURSIVE t(n, k, depth) AS (
+    VALUES (0, 0, 0)
+    UNION ALL
+    SELECT v.n, v.k, t.depth + 1
+    FROM t CROSS JOIN (VALUES (1, 2), (2, 1), (1, 1)) AS v(n, k)
+    WHERE t.depth < 1
+)
+SEARCH DEPTH FIRST BY k, n SET seq
+SELECT n, k, seq FROM t ORDER BY seq;
++---+---+------------------+
+| N | K | SEQ              |
++---+---+------------------+
+| 0 | 0 | [{0, 0}]         |
+| 1 | 1 | [{0, 0}, {1, 1}] |
+| 2 | 1 | [{0, 0}, {1, 2}] |
+| 1 | 2 | [{0, 0}, {2, 1}] |
++---+---+------------------+
+(4 rows)
+
+!ok
+
+# NULL keys sort after non-null keys within a level.
+WITH RECURSIVE t(n, depth) AS (
+    VALUES (0, 0)
+    UNION ALL
+    SELECT v.n, t.depth + 1
+    FROM t CROSS JOIN (VALUES (CAST(NULL AS INTEGER)), (2), (1)) AS v(n)
+    WHERE t.depth < 1
+)
+SEARCH BREADTH FIRST BY n SET seq
+SELECT n FROM t ORDER BY seq;
++---+
+| N |
++---+
+| 0 |
+| 1 |
+| 2 |
+|   |
++---+
+(4 rows)
+
+!ok
+
+# The generated column is included in SELECT * and available to a later CTE.
+WITH RECURSIVE "Walk"("Node") AS (
+    VALUES (1)
+    UNION ALL
+    SELECT "Node" + 1 FROM "Walk" WHERE "Node" < 3
+)
+SEARCH DEPTH FIRST BY "Node" SET "Sequence",
+u AS (SELECT * FROM "Walk")
+SELECT "Node" FROM u ORDER BY "Sequence";
++------+
+| Node |
++------+
+|    1 |
+|    2 |
+|    3 |
++------+
+(3 rows)
+
+!ok
+
+# SEARCH and CYCLE can be combined. The row closing the cycle is returned.
+WITH RECURSIVE t(n, depth) AS (
+    VALUES (1, 0)
+    UNION ALL
+    SELECT MOD(n + 1, 3), depth + 1 FROM t WHERE depth < 5
+)
+SEARCH DEPTH FIRST BY n SET seq
+CYCLE n SET is_cycle USING cycle_path
+SELECT n, is_cycle, CARDINALITY(cycle_path) AS path_length
+FROM t ORDER BY seq;
++---+----------+-------------+
+| N | IS_CYCLE | PATH_LENGTH |
++---+----------+-------------+
+| 1 | false    |           1 |
+| 2 | false    |           2 |
+| 0 | false    |           3 |
+| 1 | true     |           4 |
++---+----------+-------------+
+(4 rows)
+
+!ok
+
+# Multiple roots and UNION DISTINCT: duplicate seed rows are eliminated.
+WITH RECURSIVE t(n) AS (
+    VALUES (2), (1), (1)
+    UNION DISTINCT
+    SELECT n + 2 FROM t WHERE n < 3
+)
+SEARCH BREADTH FIRST BY n SET seq
+SELECT * FROM t ORDER BY seq;
++---+--------+
+| N | SEQ    |
++---+--------+
+| 1 | {0, 1} |
+| 2 | {0, 2} |
+| 3 | {1, 3} |
+| 4 | {1, 4} |
++---+--------+
+(4 rows)
+
+!ok
+
+# UNION DISTINCT removes duplicate recursive rows, including their SEARCH keys.
+# Repeated edges produce the same path twice at each recursive step.
+WITH RECURSIVE edges(src, dst) AS (
+    VALUES (0, 1), (0, 1), (1, 2), (1, 2)
+),
+walk(node) AS (
+    VALUES (0)
+    UNION DISTINCT
+    SELECT e.dst FROM walk w JOIN edges e ON e.src = w.node
+)
+SEARCH DEPTH FIRST BY node SET seq
+SELECT * FROM walk ORDER BY seq;
++------+-----------------+
+| NODE | SEQ             |
++------+-----------------+
+|    0 | [{0}]           |
+|    1 | [{0}, {1}]      |
+|    2 | [{0}, {1}, {2}] |
++------+-----------------+
+(3 rows)
+
+!ok
+
+# Duplicate recursive rows also have identical BREADTH keys and are eliminated.
+WITH RECURSIVE edges(src, dst) AS (
+    VALUES (0, 1), (0, 1), (1, 2), (1, 2)
+),
+walk(node) AS (
+    VALUES (0)
+    UNION DISTINCT
+    SELECT e.dst FROM walk w JOIN edges e ON e.src = w.node
+)
+SEARCH BREADTH FIRST BY node SET seq
+SELECT * FROM walk ORDER BY seq;
++------+--------+
+| NODE | SEQ    |
++------+--------+
+|    0 | {0, 0} |
+|    1 | {1, 1} |
+|    2 | {2, 2} |
++------+--------+
+(3 rows)
+
+!ok
+
+# UNION DISTINCT compares the generated SEARCH column as well as node.
+# In this diamond, node 3 survives twice because the DEPTH paths differ.
+WITH RECURSIVE edges(src, dst) AS (
+    VALUES (0, 1), (0, 2), (1, 3), (2, 3)
+),
+walk(node) AS (
+    VALUES (0)
+    UNION DISTINCT
+    SELECT e.dst FROM walk w JOIN edges e ON e.src = w.node
+)
+SEARCH DEPTH FIRST BY node SET seq
+SELECT * FROM walk ORDER BY seq;
++------+-----------------+
+| NODE | SEQ             |
++------+-----------------+
+|    0 | [{0}]           |
+|    1 | [{0}, {1}]      |
+|    3 | [{0}, {1}, {3}] |
+|    2 | [{0}, {2}]      |
+|    3 | [{0}, {2}, {3}] |
++------+-----------------+
+(5 rows)
+
+!ok
+
+# Node 3 survives at two depths because its BREADTH keys differ.
+WITH RECURSIVE edges(src, dst) AS (
+    VALUES (0, 1), (1, 3), (0, 3)
+),
+walk(node) AS (
+    VALUES (0)
+    UNION DISTINCT
+    SELECT e.dst FROM walk w JOIN edges e ON e.src = w.node
+)
+SEARCH BREADTH FIRST BY node SET seq
+SELECT * FROM walk ORDER BY seq;
++------+--------+
+| NODE | SEQ    |
++------+--------+
+|    0 | {0, 0} |
+|    1 | {1, 1} |
+|    3 | {1, 3} |
+|    3 | {2, 3} |
++------+--------+
+(4 rows)
+
+!ok
+
+# A search key also works in a descending, multi-column sort with a limit.
+WITH RECURSIVE edges(src, dst) AS (
+    VALUES (0, 2), (0, 1), (1, 4), (2, 3)
+),
+walk(node) AS (
+    VALUES (0)
+    UNION ALL
+    SELECT e.dst FROM walk w JOIN edges e ON e.src = w.node
+)
+SEARCH DEPTH FIRST BY node SET seq
+SELECT node FROM walk ORDER BY seq DESC, node FETCH NEXT 3 ROWS ONLY;
++------+
+| NODE |
++------+
+|    3 |
+|    2 |
+|    4 |
++------+
+(3 rows)
+
+!ok
+
+# SEARCH cannot create rows when the seed is empty.
+WITH RECURSIVE t(n) AS (
+    SELECT n FROM (VALUES (1)) AS v(n) WHERE FALSE
+    UNION ALL
+    SELECT n + 1 FROM t WHERE n < 3
+)
+SEARCH BREADTH FIRST BY n SET seq
+SELECT n FROM t ORDER BY seq;
++---+
+| N |
++---+
++---+
+(0 rows)
+
+!ok
+
+# SEARCH keys must name columns of the WITH item.
+WITH RECURSIVE t(n) AS (
+    VALUES (1) UNION ALL SELECT n + 1 FROM t WHERE n < 3
+)
+SEARCH DEPTH FIRST BY missing SET seq
+SELECT * FROM t;
+SEARCH column 'MISSING' is not a column of WITH item 'T'
+!error
+
+# The generated search column must have a fresh name.
+WITH RECURSIVE t(n) AS (
+    VALUES (1) UNION ALL SELECT n + 1 FROM t WHERE n < 3
+)
+SEARCH BREADTH FIRST BY n SET n
+SELECT * FROM t;
+SEARCH generated column 'N' conflicts with another column
+!error
+
+# Generated columns are not visible in the user's recursive term.
+WITH RECURSIVE t(n) AS (
+    VALUES (1) UNION ALL SELECT n FROM t WHERE seq IS NOT NULL
+)
+SEARCH DEPTH FIRST BY n SET seq
+SELECT * FROM t;
+Column 'SEQ' not found in any table
+!error
+
 # End recursive_queries.iq
diff --git a/site/_docs/reference.md b/site/_docs/reference.md
index 294f701f26..18a3b5d097 100644
--- a/site/_docs/reference.md
+++ b/site/_docs/reference.md
@@ -205,6 +205,7 @@ ## Grammar
       name
       [ '(' column [, column ]* ')' ]
       AS '(' query ')'
+      [ SEARCH { DEPTH | BREADTH } FIRST BY column [, column ]* SET 
orderColumn ]
       [ CYCLE column [, column ]* SET markColumn
           [ TO cycleValue DEFAULT nonCycleValue ] USING pathColumn ]
 
@@ -562,6 +563,59 @@ ## Grammar
 ON left_table.col = right_table.col
 ```
 
+### Search ordering in recursive queries
+
+`SEARCH` generates a column that can be used to order the output of a recursive
+query. `SEARCH DEPTH FIRST` orders a node before its descendants and those
+descendants before the next sibling. `SEARCH BREADTH FIRST` orders by depth,
+then by the specified columns within each level. The columns in `BY` are
+compared in their listed order. For a generated search column named `seq`,
+with `ORDER BY seq ASC`, nested NULL key values compare after non-NULL values.
+`ORDER BY seq DESC` reverses the ordering of the entire search key.
+`NULLS FIRST` and `NULLS LAST` have no effect because `seq` itself is never 
NULL.
+
+For example:
+
+{% highlight sql %}
+WITH RECURSIVE
+  edges(src, dst) AS (VALUES (0, 2), (0, 1), (1, 4), (2, 3)),
+  walk(node) AS (
+    VALUES (0)
+    UNION ALL
+    SELECT e.dst FROM walk AS w JOIN edges AS e ON e.src = w.node
+  ) SEARCH DEPTH FIRST BY node SET search_order
+SELECT node FROM walk ORDER BY search_order;
+{% endhighlight %}
+
+This returns `0, 1, 4, 2, 3`. Changing `DEPTH` to `BREADTH` returns
+`0, 1, 2, 3, 4`. `SEARCH` does not itself sort the result or control the
+physical evaluation order; use an explicit `ORDER BY` on the generated column.
+Rows with equal search keys have no guaranteed relative order.
+
+The depth-first column is an array of key rows representing the path. The
+breadth-first column is a row containing the depth (starting at zero) and the
+current keys. The generated column is appended to the WITH item's output,
+including `SELECT *`, but is not part of its declared column list and cannot
+be referenced in the recursive term.
+
+The generated search column participates in duplicate elimination by `UNION`
+(or `UNION DISTINCT`). Therefore, the same node may appear more than once if
+its search keys differ, for example because it is reached through different
+paths with `DEPTH FIRST` or at different depths with `BREADTH FIRST`.
+Rows that are identical in all columns, including the search column, are
+still eliminated as duplicates.
+
+`SEARCH` requires `WITH RECURSIVE` and a binary `UNION` or `UNION ALL` whose
+recursive operand is a `SELECT` with exactly one direct reference to the
+WITH item on a non-null-generating side of a join. Aggregation, `DISTINCT`,
+and window functions in that operand are not supported. The `BY` columns
+must be distinct columns of the WITH item, and the generated column's name
+must not conflict with any other output column.
+
+`SEARCH` can be combined with `CYCLE`, in that order. The search column is
+followed by the cycle mark and path columns. Search ordering alone does not
+detect or stop cycles.
+
 ### Cycle detection in recursive queries
 
 `CYCLE` tracks the specified columns along each path through a recursive
diff --git 
a/testkit/src/main/java/org/apache/calcite/sql/parser/SqlParserTest.java 
b/testkit/src/main/java/org/apache/calcite/sql/parser/SqlParserTest.java
index 3c4b9ca435..fb406c4f46 100644
--- a/testkit/src/main/java/org/apache/calcite/sql/parser/SqlParserTest.java
+++ b/testkit/src/main/java/org/apache/calcite/sql/parser/SqlParserTest.java
@@ -2745,6 +2745,81 @@ void checkPeriodPredicate(Checker checker) {
     sql(sql).ok(expected);
   }
 
+  /** Test case for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7815";>[CALCITE-7815]
+   * Support the SQL-standard SEARCH clause in recursive CTEs</a>. */
+  @Test void testWithSearch() {
+    for (String mode : new String[]{"DEPTH", "BREADTH"}) {
+      sql("WITH RECURSIVE t(n) AS (VALUES (1) UNION ALL SELECT n FROM t)\n"
+          + "SEARCH " + mode + " FIRST BY n SET seq SELECT * FROM t")
+          .ok("WITH RECURSIVE `T` (`N`) AS ((VALUES (ROW(1)))\n"
+              + "UNION ALL\n"
+              + "SELECT `N`\n"
+              + "FROM `T`) SEARCH " + mode + " FIRST BY `N` SET `SEQ` SELECT 
*\n"
+              + "FROM `T`");
+    }
+  }
+
+  @Test void testWithSearchCompositeKey() {
+    for (String mode : new String[]{"DEPTH", "BREADTH"}) {
+      sql("WITH RECURSIVE t(\"Key\", depth) AS (VALUES (1, 0)\n"
+          + "UNION ALL SELECT \"Key\", depth + 1 FROM t)\n"
+          + "SEARCH " + mode + " FIRST BY \"Key\", depth SET \"Sequence\" 
SELECT * FROM t")
+          .ok("WITH RECURSIVE `T` (`Key`, `DEPTH`) AS ((VALUES (ROW(1, 0)))\n"
+              + "UNION ALL\n"
+              + "SELECT `Key`, (`DEPTH` + 1)\n"
+              + "FROM `T`) SEARCH " + mode + " FIRST BY `Key`, `DEPTH`"
+              + " SET `Sequence` SELECT *\n"
+              + "FROM `T`");
+    }
+  }
+
+  @Test void testWithSearchFollowingWithItem() {
+    sql("WITH RECURSIVE t(n) AS (VALUES (1) UNION ALL SELECT n FROM t)\n"
+        + "SEARCH BREADTH FIRST BY n SET seq, u AS (SELECT * FROM t) SELECT * 
FROM u")
+        .ok("WITH RECURSIVE `T` (`N`) AS ((VALUES (ROW(1)))\n"
+            + "UNION ALL\n"
+            + "SELECT `N`\n"
+            + "FROM `T`) SEARCH BREADTH FIRST BY `N` SET `SEQ`, `U` AS (SELECT 
*\n"
+            + "FROM `T`) SELECT *\n"
+            + "FROM `U`");
+  }
+
+  @Test void testWithSearchAndCycle() {
+    sql("WITH RECURSIVE t(n) AS (VALUES (1) UNION ALL SELECT n FROM t)\n"
+        + "SEARCH DEPTH FIRST BY n SET seq CYCLE n SET c USING p SELECT * FROM 
t")
+        .ok("WITH RECURSIVE `T` (`N`) AS ((VALUES (ROW(1)))\n"
+            + "UNION ALL\n"
+            + "SELECT `N`\n"
+            + "FROM `T`) SEARCH DEPTH FIRST BY `N` SET `SEQ`"
+            + " CYCLE `N` SET `C` TO TRUE DEFAULT FALSE USING `P` SELECT *\n"
+            + "FROM `T`");
+  }
+
+  @Test void testWithSearchFails() {
+    final String prefix = "WITH RECURSIVE t(n) AS (VALUES (1) UNION ALL SELECT 
n FROM t)\n";
+    sql(prefix + "SEARCH ^FIRST^ BY n SET seq SELECT * FROM t")
+        .fails("(?s)Encountered \"FIRST\" at .*Was 
expecting.*\"BREADTH\".*\"DEPTH\".*");
+    sql(prefix + "SEARCH DEPTH ^BY^ n SET seq SELECT * FROM t")
+        .fails("(?s)Encountered \"BY\" at .*Was expecting.*\"FIRST\".*");
+    sql(prefix + "SEARCH BREADTH FIRST ^n^ SET seq SELECT * FROM t")
+        .fails("(?s)Encountered \"n\" at .*Was expecting.*\"BY\".*");
+    // BY requires a non-empty list of column names, not expressions.
+    sql(prefix + "SEARCH DEPTH FIRST BY ^SET^ seq SELECT * FROM t")
+        .fails("(?s)Incorrect syntax near the keyword 'SET' at .*Was 
expecting.*<IDENTIFIER>.*");
+    sql(prefix + "SEARCH DEPTH FIRST BY n, ^SET^ seq SELECT * FROM t")
+        .fails("(?s)Incorrect syntax near the keyword 'SET' at .*Was 
expecting.*<IDENTIFIER>.*");
+    sql(prefix + "SEARCH DEPTH FIRST BY n ^+^ 1 SET seq SELECT * FROM t")
+        .fails("(?s)Encountered \"\\+\" at .*Was expecting.*\"SET\".*");
+    sql(prefix + "SEARCH DEPTH FIRST BY n ^SELECT^ * FROM t")
+        .fails("(?s)Encountered \"SELECT\" at .*Was expecting.*\"SET\".*");
+    sql(prefix + "SEARCH DEPTH FIRST BY n SET ^SELECT^ * FROM t")
+        .fails("(?s)Incorrect syntax near the keyword 'SELECT' at .*Was 
expecting.*<IDENTIFIER>.*");
+    // SEARCH must precede CYCLE.
+    sql(prefix + "CYCLE n SET c USING p ^SEARCH^ DEPTH FIRST BY n SET seq 
SELECT * FROM t")
+        .fails("(?s)Incorrect syntax near the keyword 'SEARCH' at .*Was 
expecting.*");
+  }
+
   @Test void testWithCycle() {
     sql("WITH RECURSIVE t(n) AS (VALUES (1) UNION ALL SELECT n FROM t)\n"
         + "CYCLE n SET c TO 'Y' DEFAULT 'N' USING p SELECT * FROM t")

Reply via email to