As far as I know, at least in SQL Server, we can’t use an alias from a table in a set that is being used to join with that table.
In an example:
CREATE TABLE A (A1 int, A2 int)
CREATE TABLE B (B1 int, B2 int)
SELECT a.A2
FROM
A as a
INNER JOIN
(SELECT * FROM B as b WHERE b.B1=a.A1) b2 ON b2.B2=a.A2
That query will result in an error because the alias a is being used in the set that would be joined to the table where the alias refer (A).
In SQL Server this could be solved using the CROSS APPLY, or maybe by re-writing the query. (This is NOT my question).
My question is: Why does this restriction exists?, why not let use the alias as the SQL Server CROSS APPLY?
My first guess is: Parallelism. If we can restrict this, each set that appear to be joined could always be computed in parallel and then joined. But it is just a guess. It could be more flexible and let me use the alias and compute dependencies between joining sets as I guess does CROSS APPLY.
Maybe there isn’t a why 🙂
The restriction exists because of the scoping rules for standard SQL. One table in a
fromclause just doesn’t know what is happening inside another table. Remember, SQL is a descriptive language not a procedural language. The order of the tables in thefromclause is not at all necessarily related to the actual order they are processed in.This restriction does not apply in
SELECT,WHERE, andHAVINGclauses, because theFROMclause is evaluated first.As for the
cross applybeing the same or different from ajoin. There are many ways to write joins and the explicitjoinsyntax is just one of them. Correlated subqueries, nested queries inselects,existswith subqueries, andinwith subqueries are all performing some variant of the relational join operation. They are expressed differently.The uses of
cross applywith a subquery are also, generally, types of joins. There may be some cases with very complex queries with nested uses of windows function where it may not be possible to rewrite the query as an explicit join. In most cases, though, I have been able to.