Why This Error Happens
Error 5366 occurs when a T-SQL query attempts to use a ranking, aggregate, or analytic function (such as RANK(), LAG(), SUM(), or ROW_NUMBER()) without specifying a required OVER clause, or when a referenced WINDOW definition lacks an ORDER BY subclause. SQL Server 2025 strictly enforces that these window functions must define how rows are partitioned and ordered before computation, as the function has no implicit way to determine row sequence otherwise. This typically stems from a syntax oversight in application-generated queries, ORM-generated SQL, or scripts migrated from older database platforms that do not require this clause.
Step-by-Step Resolution Guide
Step 1: Identify the Offending Query
- Check the SQL Server error log or SSMS output pane for the exact query text referencing error 5366.
- Use
SELECT * FROM sys.dm_exec_requestscombined withsys.dm_exec_sql_text(sql_handle)to capture the live query if it’s coming from an application connection. - Note the specific function name reported in the error message (e.g.,
RANK,DENSE_RANK,LAG).
Step 2: Add or Correct the OVER Clause
- Modify the query to include an explicit
OVERclause immediately after the function call. - Example fix: change
SELECT RANK() FROM Sales;toSELECT RANK() OVER (ORDER BY SaleDate) FROM Sales; - If partitioning is required, include
PARTITION BYinside the same clause, e.g.,OVER (PARTITION BY RegionID ORDER BY SaleDate).
Step 3: Validate Named WINDOW Definitions
- If the query uses the
WINDOWclause (introduced for reusable window specs), ensure every named window includes anORDER BYdefinition. - Example:
WINDOW w AS (PARTITION BY CustomerID ORDER BY OrderDate)instead ofWINDOW w AS (PARTITION BY CustomerID). - Re-run the query in SSMS or Azure Data Studio to confirm the parser no longer raises error 5366.
Step 4: Update Application or ORM-Generated SQL
- If the query originates from an ORM (Entity Framework, Hibernate, etc.), check the generated SQL template for missing
ORDER BYlogic in ranking functions. - Patch the ORM mapping or raw SQL override to always inject an
ORDER BYcolumn when generating window functions. - Deploy the corrected query/application build to a test environment before pushing to production on Windows Server 2025.
Alternative or Verification Steps
- Re-execute the corrected query directly in SQL Server Management Studio (SSMS) connected to the SQL Server 2025 instance and confirm no error 5366 is returned.
- If the issue persists in a packaged application, enable SQL Server Profiler or Extended Events to trace the exact query being sent at runtime, then compare it against your corrected version to catch any caching of the old query plan.