How to fix Error 5308 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 5308 – Windowed Functions

Why This Error Happens

Error 5308 occurs when a windowed function (such as ROW_NUMBER(), RANK(), LAG(), or LEAD()) is used with an invalid ORDER BY clause or an unsupported frame specification within the OVER() clause. This typically happens when the database compatibility level is set too low to support the specific windowing syntax being used, or when a ROWS/RANGE frame is combined with a function that does not support frame clauses (like LAG or LEAD). Corrupted query plans cached from a previous SQL Server version during an in-place upgrade to SQL Server 2025 can also trigger this error unexpectedly.

Step-by-Step Resolution Guide

Step 1: Verify Database Compatibility Level

  • Open SQL Server Management Studio (SSMS) and connect to your SQL Server 2025 instance.
  • Run the following query to check the current compatibility level: SELECT name, compatibility_level FROM sys.databases WHERE name = 'YourDatabaseName';
  • If the level is below 160 (SQL Server 2022) or 170 (SQL Server 2025), update it using: ALTER DATABASE YourDatabaseName SET COMPATIBILITY_LEVEL = 170;

Step 2: Review and Correct the OVER() Clause Syntax

  • Inspect the specific query triggering the error in the SQL Server error log located at C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Log\ERRORLOG.
  • Ensure that LAG() and LEAD() functions do not include a ROWS BETWEEN or RANGE BETWEEN frame specification, as this is unsupported.
  • Confirm that ORDER BY columns referenced in the windowed function actually exist in the underlying table or CTE and are not ambiguous.

Step 3: Clear the Procedure Cache

  • Corrupted or stale execution plans from a pre-upgrade environment can cause phantom 5308 errors.
  • Run DBCC FREEPROCCACHE; to clear the plan cache for the instance (use with caution in production environments during off-peak hours).
  • Re-execute the failing query to see if a fresh execution plan resolves the parsing error.

Step 4: Apply the Latest Cumulative Update (CU)

  • Navigate to the Microsoft Update Catalog and search for the latest Cumulative Update for SQL Server 2025.
  • Download and run the update package on your Windows Server 2025 host.
  • Restart the SQL Server (MSSQLSERVER) service via services.msc or by running net stop MSSQLSERVER && net start MSSQLSERVER in an elevated Command Prompt.

Alternative or Verification Steps

  • Verify the Fix: Run the query in a new SSMS query window (Ctrl+N) to ensure the parser accepts the syntax without using a cached, broken execution plan.
  • Alternative Workaround: If the error persists specifically with LAG/LEAD, rewrite the logic using a ROW_NUMBER() subquery combined with a self-join to achieve the same lookahead/lookbehind result without triggering the frame specification conflict.