Why doesn't the following work?
SELECT name FROM (SELECT name FROM agentinformation)
I guess my understanding of SQL is wrong, because I would have thought this would return the same thing as
SELECT name FROM agentinformation
Doesn't the inner select statement create a result set which the outer SELECT statement then queries?
You need to alias the subquery.
SELECT name FROM (SELECT name FROM agentinformation) a
or to be more explicit
SELECT a.name FROM (SELECT name FROM agentinformation) a
Answer provided by Joe Stefanelli is already correct.
SELECT name FROM (SELECT name FROM agentinformation) as a
We need to make alias of subquery because query needs table object which we will get from making an alias to subquery. Conceptually, the subquery results are substituted into the outer query. As we need table object in outer query, we need to make an alias of inner query.
Statements that include a subquery usually take one of these formats:
- WHERE expression [NOT] IN (subquery)
- WHERE expression comparison_operator [ANY | ALL] (subquery)
- WHERE [NOT] EXISTS (subquery)
Check for more subquery rules and subquery types.
More examples of Nested Subquery.
IN / NOT IN – This operator takes the output of inner query after inner query gets executed which can be zero or more values and send it to outer query. The outer query then fetches all the matching [IN operator] or not non matching [NOT IN operator] rows.
ANY – [>ANY or ANY operator takes the list of values produced by inner query and fetches all the values which are greater than the minimum value of the list. The
e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.
- ALL – [>ALL or ALL operator takes the list of values produced by inner query and fetches all the values which are greater than the maximum of the list. The
e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.
- EXISTS - The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.
来源:https://stackoverflow.com/questions/4629979/nested-select-statement-in-sql-server