Why does the following query work, when there is no column named Agentid in the “NewAccounts”-CTE?
WITH
NewAccounts AS (
SELECT 3 as Newaccountid
),
MovedAUM AS (
SELECT 1 AS Agentid, 2 as Col2
)
SELECT * FROM MovedAUM WHERE agentid IN (SELECT Agentid FROM NewAccounts)
The following, modified query returns the error message as expected:
WITH
NewAccounts AS (
SELECT 3 AS newaccountid
)
SELECT Agentid FROM NewAccounts
The first one works because
MovedAUMis in scope within the nestedSELECT. It is actually returningMovedAUM.AgentIdfor each row inNewAccounts. In other words theWHEREclause is doing nothing – it’s equivalent toWHERE 1 = 1.This slightly modified version will fail: