Published on

May 24, 2012

Understanding Error 147 in SQL Server

As a beginner in SQL Server, it’s common to encounter errors and get stuck while trying to solve a problem. One such error is Error 147, which can be confusing if you’re not familiar with the concept of aggregates and the proper usage of WHERE and HAVING clauses.

In this blog post, we will discuss the cause of Error 147 and provide a solution to fix it. Let’s dive in!

The Problem

Imagine you have a table called SalesOrderHeader, and you want to find all the details of sales orders with the latest ShipDate. A beginner might come up with the following T-SQL query:

SELECT *
FROM [Sales].[SalesOrderHeader]
WHERE ShipDate = MAX(ShipDate)

However, executing this query will result in Error 147:

Msg 147, Level 15, State 1, Line 3
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

This error occurs because the MAX() function is being used in the WHERE clause, which is not allowed. The solution is to use a subquery to retrieve the maximum ShipDate and then compare it in the WHERE clause.

The Solution

To fix Error 147, we need to modify the query as follows:

SELECT *
FROM [Sales].[SalesOrderHeader]
WHERE ShipDate = (SELECT MAX(ShipDate) FROM [Sales].[SalesOrderHeader])

By using a subquery, we can retrieve the maximum ShipDate and compare it in the WHERE clause. This will give us the desired result without generating any errors.

It’s important to note that there are often multiple solutions to a single problem in SQL Server. However, in this case, using a subquery is the most straightforward and efficient solution.

Conclusion

Error 147 in SQL Server can be frustrating for beginners, but understanding the concept of aggregates and the proper usage of WHERE and HAVING clauses can help resolve this issue. By using a subquery to retrieve the maximum ShipDate, we can avoid the error and get the desired results.

If you have encountered Error 147 or have any other solutions to the problem stated, please share them in the comments below. Happy coding!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.