If you’re getting error message 4112 that reads “The function ‘LAG’ must have an OVER clause with ORDER BY” in SQL Server, it’s probably because you’re omitting the ORDER BY clause from the OVER clause when using the LAG() function.
The LAG() function requires an OVER clause that contains an ORDER BY clause. This error happens when we include the OVER clause but not the ORDER BY clause.
To fix this error, add an ORDER BY clause to the OVER clause.
Example of Error
Here’s an example of code that results in the error:
SELECT
VendorId,
ProductName,
ProductPrice,
LAG( ProductPrice ) OVER ( ) AS LAG
FROM Products;
Result:
Msg 4112, Level 15, State 1, Line 5 The function 'LAG' must have an OVER clause with ORDER BY.
The error occurred because, although I provided an OVER clause, it doesn’t contain an ORDER BY clause.
Note that simply adding an ORDER BY clause to the end of the query does not fix the issue:
SELECT
VendorId,
ProductName,
ProductPrice,
LAG( ProductPrice ) OVER ( ) AS LAG
FROM Products
ORDER BY ProductPrice;
Result:
Msg 4112, Level 15, State 1, Line 5 The function 'LAG' must have an OVER clause with ORDER BY.
While it’s fine to have an ORDER BY clause at the end of the query, there still needs to be one in the OVER clause.
Solution
To fix this issue, all we need to do is add an ORDER BY clause to the OVER clause:
SELECT
VendorId,
ProductName,
ProductPrice,
LAG( ProductPrice ) OVER (
ORDER BY ProductPrice
) AS LAG
FROM Products;
Result:
VendorId ProductName ProductPrice LAG -------- ------------------------------- ------------ ----- 1004 Bottomless Coffee Mugs (4 Pack) 9.99 null 1003 Hammock 10 9.99 1001 Long Weight (green) 11.99 10 1004 Tea Pot 12.45 11.99 1001 Long Weight (blue) 14.75 12.45 1001 Left handed screwdriver 25.99 14.75 1001 Right handed screwdriver 25.99 25.99 1002 Sledge Hammer 33.49 25.99 1003 Straw Dog Box 55.99 33.49 1003 Chainsaw 245 55.99
This time the function worked as expected, without error.
The OVER clause can also have a PARTITION BY clause, but this is optional. We can omit the PARTITION BY clause, but not the ORDER BY clause.