Yibo Dong created SPARK-62281:
---------------------------------
Summary: HAVING applies incorrect type coercion to a SELECT alias
shadowing an input column
Key: SPARK-62281
URL: https://issues.apache.org/jira/browse/SPARK-62281
Project: Spark
Issue Type: Bug
Components: SQL
Affects Versions: 5.0.0
Environment: Stock Apache Spark 5.0.0-SNAPSHOT at commit
082cf160890a0a0a748f70ffb5a993144b0de079, Java 25.0.1, macOS 15.7.4 aarch64,
local[2], in-memory session catalog, built-in Parquet data source (V1), default
SQL configuration.
Reporter: Yibo Dong
When a SELECT alias shadows a non-grouped input column of a different type,
HAVING resolves the alias correctly but retains type coercions derived from the
input column.
For example, in SELECT c AS a ... GROUP BY c HAVING a = '10', the input column
a is INT while the SELECT alias a is STRING. Spark incorrectly performs numeric
comparison instead of string comparison, returning extra rows or raising
CAST_INVALID_INPUT for non-numeric strings.
h2. How to reproduce
Run the following SQL in a fresh Spark SQL session:
{code:sql}
CREATE OR REPLACE TEMP VIEW t(a, c) AS
VALUES (1, '010'), (2, '10'), (3, 'x');
-- Q1: Equality on a STRING alias shadowing an INT column.
SELECT c AS a, count(*) AS n
FROM t WHERE c <> 'x'
GROUP BY c HAVING a = '10';
-- Q2: Ordering comparison on the same alias.
SELECT c AS a, count(*) AS n
FROM t WHERE c <> 'x'
GROUP BY c HAVING a > '9';
-- Control: use a non-conflicting alias.
SELECT c AS k, count(*) AS n
FROM t WHERE c <> 'x'
GROUP BY c HAVING k = '10';
-- Control: filter the aggregate in a derived table.
SELECT *
FROM (
SELECT c AS a, count(*) AS n
FROM t WHERE c <> 'x'
GROUP BY c
)
WHERE a = '10';
-- Q3: Non-numeric string comparison.
SELECT c AS a, count(*) AS n
FROM t GROUP BY c HAVING a = 'x';
{code}
Save as tmp.sql and execute:
{code:bash}
spark-sql --master 'local[2]' --conf spark.sql.catalogImplementation=in-memory
-f tmp.sql
{code}
h2. Expected result
The alias a is STRING, so all HAVING predicates should use string comparisons.
Q1 should return only (10, 1), matching both controls, because '010' != '10'.
Q2 should return no rows because neither '010' nor '10' is lexicographically
greater than '9'.
Q3 should return (x, 1) without an error.
h2. Actual result
Q1 returns two rows:
{noformat}
a | n
----+---
010 | 1
10 | 1
{noformat}
Q2 also returns both rows:
{noformat}
a | n
----+---
010 | 1
10 | 1
{noformat}
Both controls return only (10, 1).
Q3 fails with:
{noformat}
[CAST_INVALID_INPUT] The value 'x' of the type "STRING"
cannot be cast to "BIGINT" because it is malformed.
SQLSTATE: 22018
{noformat}
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]