Introduction
A few days ago, I found an extraordinary thing with SQL SERVER 2005, and I strongly feel that this is a bug in SQL Server that can create lots of data discrepancies.
Let's go through the script.
- Create a new fresh database.
- Use this Database.
- Create a table name tblCategory.
- Create another table named tblProduct.
- Insert 5 rows in tblCategory.
- Insert 10 rows in tblProduct.
- Select statements to confirm that data is entered or not.
- Here is a select query that is incorrect. The query tells us to select ProductID from tblCategory where categoryId = 1, But the tblCategory table does not have a column named ProductID. So when we execute this query, it throws an error, which is the expected behavior.
- Here is the magic. I have used the above incorrect select query with an update statement as an inner query. What do you think? What should happen when you execute this query? This query should throw an error as my inner select query is incorrect. But execute this query, and you will be shocked.
- Oops!!!! All the data in IsDamaged is set to 1, but my inner select query(SELECT ProductID FROM tblCategory WHERE CategoryID = 1) is wrong. 10 rows were affected.
Initially, I thought this was a bug, but it's not. The inner query first tries to find the column in the current table (inner query's table), and if it is not found, it will look for the outer query table. It is the best practice to use the tableName.ColumnName in the inner query.
Now this inner query will throw an error. So next time, be careful whenever you are working with inner queries.