Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

[SPARK-62678][SQL] Compare row values field by field so NULL fields make comparisons and IS [NOT] NULL follow SQL - #61190

Draft
linhongliu-db wants to merge 6 commits into
apache:masterfrom
linhongliu-db:fix-row-value-comparison-null-fields
Draft

linhongliu-db wants to merge 6 commits into
apache:masterfrom
linhongliu-db:fix-row-value-comparison-null-fields

Conversation

@linhongliu-db

@linhongliu-db linhongliu-db commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

What changes were proposed in this pull request?

The parser turns a row value constructor (a, b) into a struct (AstBuilder.visitRowConstructor builds CreateStruct), and visitComparison then compares the two structs. Struct ordering treats a NULL field as an ordinary value that sorts first. ISO/IEC 9075-2 compares row values field by field instead (8.2), and defines IS [NOT] NULL on a row value per field (8.8).

This PR changes how the parser builds these predicates:

  1. When both operands of =, ==, <>, !=, <, <=, >, >= are row value constructors of the same degree, they are compared field by field:
    • (a, b) = (x, y) becomes a = x AND b = y, and <> becomes NOT (a = x AND b = y). A join on row values therefore plans as a multi-key equi-join.
    • (a, b) < (x, y) means a < x OR (a = x AND b < y). <=, > and >= work the same way: every field but the last uses the strict operator, and the last field uses the operator as written. The parser emits an internal function (row_value_lt, row_value_le, row_value_gt, row_value_ge, in the internal function registry) that builds a new RuntimeReplaceable expression, RowValueOrdering, once the fields are resolved. It is built as IF(a = x, b < y, a < x), which gives the same result, NULL included. Only the predicate of IF is always evaluated, so subexpression elimination does not evaluate a field early that an enclosing AND/OR operand guards. For example, x = 0 OR (10 / x, b) < (5, 1) does not fail with DIVIDE_BY_ZERO under ANSI mode. Every field but the last can be read twice, and two reads of a nondeterministic field can disagree. So when such a field is nondeterministic, such as (rand(), b) < (0.5, 1), the coerced fields are compared by RowValueOrderingOnce, as Right does for nondeterministic arguments. It reads each field at most once, and only while the earlier pairs are equal, so it is still field-wise and NULL-aware, and stays lazy under AND/OR and in lambdas. A With would have computed the field in a project below the operator. Like the struct comparison it replaces, an ordering comparison is not pushed down to data sources. Equality is.
    • Redundant parentheses and aliases (((a, b)), (a AS p, b)) are looked through.
  2. When the operand of IS NULL / IS NOT NULL is a row value constructor, (a, b) IS NULL becomes a IS NULL AND b IS NULL and (a, b) IS NOT NULL becomes a IS NOT NULL AND b IS NOT NULL. So (1, NULL) is neither NULL nor NOT NULL. NOT ((a, b) IS NULL) keeps the NOT over the expanded IS NULL.
  3. Both changes are controlled by one new internal conf, spark.sql.legacy.rowValueComparison.asStruct (default false). Setting it to true restores the struct semantics.

Unchanged: real STRUCT values (columns, struct(...), named_struct(...), structs built with the DataFrame API) and <=> / IS [NOT] DISTINCT FROM. Also unchanged:

  • row value constructors of different degrees (same analysis error as today);
  • a row value with a star field, such as (t.*, c), because its degree is not known until the star is expanded;
  • BETWEEN and CASE (a, b) WHEN;
  • the inner fields of nested rows: ((a, b), c) = ((x, y), z) still compares (a, b) and (x, y) as structs;
  • the ASOF JOIN MATCH_CONDITION;
  • IN (subquery) and [NOT] IN lists.

A TODO in AstBuilder lists these remaining struct comparisons.

Known gap: [NOT] IN lists over row values are left as they are. (w, b) NOT IN ((1, 2)) still keeps (1, NULL). They need their own design:

  • Expanding a row-value IN list field by field ((a, b) = (1, 2) OR (a, b) = (3, 4) OR ...) cannot keep the hashed InSet path for a probe with a NULL field. Measured on a prototype, a probe with a NULL field ran 40-67x slower at 100-200 list rows. At 500 rows the generated filter exceeded the 64 KB JVM method limit and fell back to non-whole-stage execution.
  • An IN-only change was proposed before and not merged: SPARK-24395 / [SPARK-24395][SQL] IN operator should return NULL when comparing struct with NULL fields #22029, closed in 2020. Reviewers there asked whether the behavior is defined by the SQL standard, whether returning false is really wrong, and noted that Hive and Presto behave like today's Spark.

That question applies to this PR too, so here is the answer. ISO/IEC 9075-2 8.2 (comparison predicate) defines (x1, ..., xn) = (y1, ..., yn) as true when every xi = yi is true, false when some xi <> yi is true, and unknown otherwise. < and the other ordering operators are decided by the first pair that is not equal, and are unknown when that pair involves a NULL. 8.8 (null predicate) says R IS NULL is true when every field of R is NULL, and R IS NOT NULL is true when no field of R is NULL. 8.4 defines IN as = ANY, so it inherits the 8.2 rules. PostgreSQL implements exactly this ("Row Constructor Comparison" and the row-wise IS NULL notes in its documentation): ROW(1, NULL) < ROW(1, 3) and ROW(1, NULL) = ROW(1, 2) are NULL, ROW(1, NULL) < ROW(2, 0) is true, ROW(NULL, NULL) IS NULL is true, and ROW(1, NULL) IS NOT NULL is false. Returning false (or true) for a NULL field turns an unknown result into a definite one, so WHERE, JOIN ON and NOT keep or drop rows that the standard leaves unknown.

Why are the changes needed?

They return wrong results. With t(id INT, w INT, b INT) holding (1, 1, NULL), (2, 1, 2), (3, NULL, 1), (4, 2, 0):

Query Before After
SELECT id FROM t WHERE (w, b) < (1, 3) 1, 2, 3 2
SELECT id FROM t WHERE (w, b) <> (1, 2) 1, 3, 4 3, 4
SELECT (w, b) = (1, 2) FROM t WHERE id = 1 false NULL
SELECT l.id FROM t l JOIN t r ON (l.w, l.b) = (r.w, r.b) 1, 2, 3, 4 2, 4
SELECT (NULL, NULL) IS NULL false true
SELECT (1, NULL) IS NOT NULL true false

Does this PR introduce any user-facing change?

Yes:

  • A comparison between row value constructors of the same degree, or IS [NOT] NULL on a row value constructor, can return NULL (or a different boolean) where it returned true or false before. This also applies to SQL strings passed to DataFrame methods such as filter and selectExpr.
  • The fields are now coerced pair by pair, so (rand(), id) < (0.5, 3) no longer fails with the struct type-mismatch error (DOUBLE vs DECIMAL(1,1)).
  • Generated column names change, for example ((w, b) < (1, 3)) and ((w = 1) AND (b = 2)) instead of (named_struct(w, w, b, b) < named_struct(col1, 1, col2, 3)).
  • A stream-stream join on row value equality now has one join key per field, so a query that ran such a join on an earlier version cannot restart from its checkpoint unless the legacy conf is set.

spark.sql.legacy.rowValueComparison.asStruct=true restores the previous behavior. The SQL migration guide entry (under 4.5) covers both changes and the streaming restart.

How was this patch tested?

  • New golden file sql-tests/inputs/row-value-comparison.sql, over a parquet table. It covers each operator over rows with NULL fields, rows where an earlier field decides the result, projections that return NULL, three-field rows, a JOIN ... ON row values, and IS [NOT] NULL on (NULL, NULL), (1, NULL) and (1, 2). It has controls for <=>, named_struct comparisons and IS NULL, a STRUCT column compared with named_struct under both conf values, nested rows, star fields, an IN list, NOT IN (the known gap) and different degrees. It also checks that the legacy conf brings back the old rows. With the AstBuilder change reverted, the test fails for the bug: (w, b) <> (1, 2) returns 1, 3, 4, and the plans compare structs.
  • New SQLQuerySuite tests:
    • SPARK-62678: row value ordering comparisons keep fields lazy and read each once. Under ANSI mode, x = 0 OR (f, 1) < (100, 2) and x <> 0 AND (f, 1) >= (10, 1) over a parquet table do not divide by zero, for f = 10 / x and f = 10 / x + rand(). A nondeterministic leading field is read once: one rand in the optimized plan, and filter(sequence(1, 1000), x -> (rand() + x * 0 > 0.5, 0) < (true, 1)) keeps every element. It is still field-wise: (rand() * 0, 1) < (0, CAST(NULL AS INT)) is NULL. Aggregates, window functions and scalar subqueries as leading fields are covered too.
    • SPARK-62678: STRUCT values and the Column API keep struct comparisons. Column API comparisons (struct(...) === / =!= / < / >= struct(...), isNull, isNotNull) and SQL comparisons of a STRUCT column with named_struct, over rows with NULL fields, return the same struct-semantics results with spark.sql.legacy.rowValueComparison.asStruct set to false and to true.
  • New streaming golden file sql-tests/inputs/streaming/row-value-comparison.sql (StreamingSQLQueryTestSuite): row value comparisons and IS [NOT] NULL in a streaming projection and filter, and a stream-stream join on row values, which matches no NULL keys. With the legacy conf they give the struct results again, and the join matches every row to itself.
  • The batch golden also checks that a comparison of constant rows stays foldable: round(1.234D, IF((1, 2) < (1, 3), 2, 1)) returns 1.23.
  • New ExpressionParserSuite cases for the parser shapes: each operator, three fields, aliases, redundant parentheses, nested rows, star fields, IS [NOT] NULL, NOT (... IS NULL), the unchanged cases, and the legacy conf. A new PlanParserSuite case checks that an ASOF MATCH_CONDITION over row values, also in redundant parentheses, stays a struct comparison while its ON clause is compared field by field.
  • build/sbt "catalyst/testOnly *ExpressionParserSuite *PlanParserSuite": all pass.
  • build/sbt "sql/testOnly org.apache.spark.sql.SQLQuerySuite -- -z SPARK-62678": both new cases pass.
  • build/sbt "sql/testOnly org.apache.spark.sql.SQLQueryTestSuite org.apache.spark.sql.StreamingSQLQueryTestSuite org.apache.spark.sql.expressions.ExpressionInfoSuite *AsOfJoinSQLSuite *AsOfJoinSortMergeSQLSuite": all 1043 pass, with no changes to existing golden files. That includes the ASOF goldens that compare row values and the IN-list goldens.

Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Opus 5.5

This pull request and its description were written by Isaac.

…ake comparisons and IS [NOT] NULL follow SQL

Co-authored-by: Isaac <no-reply@databricks.com>
linhongliu-db and others added 5 commits December 4, 2026 22:59
…the docs

Row value ordering comparisons are built through internal functions once the fields resolve, so
every field but the last is bound once with With, as BETWEEN does. A row value with a star field
keeps the struct comparison. The conf and migration note move to 4.5, and the note now names
what stays unchanged and the stream-stream join restart.

Co-authored-by: Isaac <no-reply@databricks.com>
Build the ordering as IF(a = x, rest, a < x), so subexpression elimination does not evaluate a
field early that an enclosing AND or OR guards, and bind only nondeterministic leading fields with
With. Report wrong-arity calls of the internal functions with WRONG_NUM_ARGS, and make the conf
doc and migration note name what is unchanged, the column names and the streaming restart.

Co-authored-by: Isaac <no-reply@databricks.com>
Two reads of a nondeterministic field can disagree, and a With is computed out of a lambda or a
short-circuiting parent, so such ordering comparisons keep the struct comparison, marked with a
TODO. Correct the docs on which field decides equality and the test name.

Co-authored-by: Isaac <no-reply@databricks.com>
…once

When a field before the last is nondeterministic, RowValueOrdering compares the coerced fields
with RowValueOrderingOnce, which reads each field at most once and only while the earlier pairs
are equal, instead of falling back to the struct comparison. Add STRUCT column and Column API
controls under both values of the legacy conf.

Co-authored-by: Isaac <no-reply@databricks.com>
RowValueOrdering is foldable when its comparison is, so a comparison of constant rows can be an
argument that must be foldable. Add a streaming golden for row value predicates, IS [NOT] NULL
and a stream-stream join on row values, under both values of the legacy conf.

Co-authored-by: Isaac <no-reply@databricks.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant