You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@spark.apache.org by "Greg Rahn (Jira)" <ji...@apache.org> on 2020/08/29 19:16:00 UTC

[jira] [Commented] (SPARK-32726) Filter by column alias in where clause

    [ https://issues.apache.org/jira/browse/SPARK-32726?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17187083#comment-17187083 ] 

Greg Rahn commented on SPARK-32726:
-----------------------------------

Standard SQL disallows references to column aliases in a {{WHERE}} clause. This restriction is imposed because when the {{WHERE}} clause is evaluated, the column value may not yet have been determined. 

In the ANSI SQL standard and ISO SQL standard, the value that is associated with a column alias does not need to be available until the ORDER BY clause is executed.

There are six parts in the conceptual order of execution of a SELECT statement from the ANSI SQL standard or ISO SQL standard perspective. If all six parts exist, the sequence is the following:
 # The FROM part is executed first.
 # The WHERE or ON part is executed second.
 # The GROUP BY part is executed third.
 # The HAVING part is executed fourth.
 # The SELECT part is executed fifth.
 # The ORDER BY part is executed last.

See also: 
 * [https://stackoverflow.com/questions/8370114/referring-to-a-column-alias-in-a-where-clause]
 * [https://dev.mysql.com/doc/refman/8.0/en/problems-with-alias.html]

 

> Filter by column alias in where clause
> --------------------------------------
>
>                 Key: SPARK-32726
>                 URL: https://issues.apache.org/jira/browse/SPARK-32726
>             Project: Spark
>          Issue Type: Improvement
>          Components: SQL
>    Affects Versions: 3.1.0
>            Reporter: Yuming Wang
>            Priority: Major
>
> {{group by}} and {{order by}} clause support it. but {{where}} does not support it:
> {noformat}
> spark-sql> select id + 1 as new_id from range(5) group by new_id order by new_id;
> 1
> 2
> 3
> 4
> 5
> spark-sql> select id + 1 as new_id from range(5) where new_id > 2;
> Error in query: cannot resolve '`new_id`' given input columns: [id]; line 1 pos 44;
> 'Project [('id + 1) AS new_id#5]
> +- 'Filter ('new_id > 2)
>    +- Range (0, 5, step=1, splits=None
> spark-sql> select id + 1 as new_id, new_id + 1 as new_new_id from range(5);
> Error in query: cannot resolve '`new_id`' given input columns: [id]; line 1 pos 25;
> 'Project [(id#12L + cast(1 as bigint)) AS new_id#10L, ('new_id + 1) AS new_new_id#11]
> +- Range (0, 5, step=1, splits=None)
> {noformat}



--
This message was sent by Atlassian Jira
(v8.3.4#803005)

---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@spark.apache.org
For additional commands, e-mail: issues-help@spark.apache.org