Fix Error “The function ‘FIRST_VALUE’ must have an OVER clause” in SQL Server

If you’re getting an error that reads “The function ‘FIRST_VALUE’ must have an OVER clause” in SQL Server, it’s probably because you’re calling the FIRST_VALUE() function without an OVER clause.

The FIRST_VALUE() function requires an OVER clause (and that clause must have an ORDER BY clause).

To fix this issue, be sure to include an OVER clause when calling the FIRST_VALUE() function.

Example of Error

Here’s an example of code that produces the error:

SELECT
    VendorId,
    ProductName,
    ProductPrice,
    FIRST_VALUE( ProductPrice )
FROM Products;

Result:

Msg 10753, Level 15, State 1, Line 5
The function 'FIRST_VALUE' must have an OVER clause.

Here I called the FIRST_VALUE() function without an OVER clause, which resulted in an error.

Solution

To fix this issue, add an OVER clause to the FIRST_VALUE() function:

SELECT
    VendorId,
    ProductName,
    ProductPrice,
    FIRST_VALUE( ProductPrice ) OVER ( 
        ORDER BY ProductPrice 
        ) AS FIRST_VALUE
FROM Products;

Result:

VendorId  ProductName                      ProductPrice  FIRST_VALUE
--------  -------------------------------  ------------  -----------
1004      Bottomless Coffee Mugs (4 Pack)  9.99          9.99       
1003      Hammock                          10            9.99       
1001      Long Weight (green)              11.99         9.99       
1004      Tea Pot                          12.45         9.99       
1001      Long Weight (blue)               14.75         9.99       
1001      Left handed screwdriver          25.99         9.99       
1001      Right handed screwdriver         25.99         9.99       
1002      Sledge Hammer                    33.49         9.99       
1003      Straw Dog Box                    55.99         9.99       
1003      Chainsaw                         245           9.99       

This time we get the expected result.

It’s also important to remember that the OVER clause needs to have an ORDER BY clause. Omitting this will cause another error.