Skip to content
Advertisement

SQL with non-existing column in where cause can be executed

Here’s my SQL

The issue is, the colA1 does not exist in TableB.

So if I just run this

Then SQL Server Management Studio will return an error:

Invalid column name ‘colA1’.

But if it is in the where cause, the first SQL can be executed as if where cause is always true.

Advertisement

Answer

Thats because SQL Server first looks for the column in TableB, fails to find it, so then looks in TableA. If you fully qualify your column names (or use table aliases) you will get the error e.g.

Essentially your query is reduced to:

Thats why you should always fully qualify your table names, ideally through the use of a short, meaningful aliases.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement