Nested select statement in SQL Server

Brennan Vincent picture Brennan Vincent · Jan 7, 2011 · Viewed 717.2k times · Source

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?

Answer

Joe Stefanelli picture Joe Stefanelli · Jan 7, 2011

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