Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server Error 335: Function Call Cannot Be Used to Match

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

SQL Server Error 335 occurs when a function is used on a column within a JOIN or WHERE clause in a way that prevents the database engine from using an index to match rows. To fix this, you must move the function call from the column side of the operator to the constant or variable side, ensuring the column remains "naked" so the optimizer can perform an index seek instead of a full table scan.

What You'll Need

  • Access to SQL Server Management Studio (SSMS) or a similar SQL query editor.
  • The specific T-SQL query or stored procedure that is triggering the error.
  • Permissions to view the table schema and existing indexes on the affected columns.
  • A development or staging environment to test the query rewrite before applying it to production.

Step-by-Step

  1. Identify the Offending Column: Examine the error message and your SQL code to find where a function is wrapping a column. Look for common functions like LEFT(), RIGHT(), SUBSTRING(), CONVERT(), CAST(), or UPPER() inside a JOIN...ON or WHERE clause. For example, a line like WHERE LEFT(UserName, 3) = 'Adm' is a primary candidate for Error 335.
  2. Analyze the Indexing: Check if the column being wrapped in the function is indexed. In SSMS, right-click the table, select Design, and check the Indexes/Keys section. If the column is part of a clustered or non-clustered index, the function call is effectively "hiding" the index from the SQL Server Optimizer, leading to the error or severe performance degradation.
  3. Rewrite the Expression for SARGability: The goal is to make the query SARGable (Search ARGumentable). This means moving the logic to the right side of the equals sign. Instead of transforming the data in the table to match your search term, transform your search term to match the data in the table.
  4. Implement a Range-Based Match: If you were using LEFT() or SUBSTRING(), replace the function with a LIKE operator and a wildcard. For example, change WHERE LEFT(EmployeeCode, 3) = 'EMP' to WHERE EmployeeCode LIKE 'EMP%'. This allows SQL Server to use the index to find all entries starting with 'EMP' without calculating a function for every single row in the table.
  5. Handle Data Type Conversions: If the error is caused by CAST() or CONVERT() (e.g., WHERE CAST(OrderDate AS DATE) = '2023-01-01'), rewrite the query to use a range. Change it to WHERE OrderDate >= '2023-01-01' AND OrderDate < '2023-01-02'. This preserves the data type of the column and allows an index seek on the OrderDate column.
  6. Apply the Change to JOIN Clauses: If the function is in a JOIN condition (e.g., JOIN TableB ON LEFT(TableA.ID, 5) = TableB.ShortID), you must evaluate if the data can be cleaned at the source. If you cannot change the data, consider creating a Computed Column (see Tips section) that stores the result of the function and indexing that computed column.
  7. Verify the Execution Plan: Run the rewritten query in SSMS and press Ctrl+L to view the Estimated Execution Plan. Look for an "Index Seek" operator. If you see an "Index Scan" or "Table Scan," the query is still not fully optimized, though it may no longer trigger Error 335.
  8. Test for Logical Equivalence: Run both the original (if it still runs) and the new query with a COUNT(*) to ensure they return the exact same number of rows. This confirms that your rewrite did not accidentally exclude data or include false positives.

Common Mistakes

One of the most frequent mistakes is attempting to fix the error by adding more indexes. Adding an index to a column does not help if the query uses a function on that column; the function essentially tells SQL Server, "I don't care about the index; calculate this value for every row first." No amount of standard indexing will solve a non-SARGable query.

Another common error is using LIKE '%term' (leading wildcard). While this removes the function call, a leading wildcard also prevents an index seek, resulting in a full index scan. While this might stop Error 335 from appearing in certain contexts, it does not solve the underlying performance issue that the error is warning you about.

Developers also often forget to handle nulls when rewriting functions. Some functions handle NULL values differently than a LIKE or a range comparison. Always check if your column allows nulls and ensure your rewritten logic maintains the same null-handling behavior as the original function call.

Tips

If you absolutely must filter by a transformed value and the table is too large for a scan, use a Persisted Computed Column. You can add a new column to your table that is defined as the result of the function (e.g., ALTER TABLE Employees ADD EmpPrefix AS LEFT(EmployeeCode, 3) PERSISTED). Once the column is persisted, you can create a standard index on EmpPrefix. Your queries can then reference EmpPrefix directly without a function call, eliminating Error 335 and maximizing speed.

When dealing with dates, always prefer range comparisons (>= and <) over DATEPART() or YEAR(). For instance, instead of WHERE YEAR(CreatedDate) = 2023, use WHERE CreatedDate >= '2023-01-01' AND CreatedDate < '2024-01-01'. This is the gold standard for SQL Server performance tuning.

Consider using a Filtered Index if you only ever search for a specific subset of data. If you frequently search for rows where a certain function would return 'Active', create an index that only includes those rows. This reduces the index size and speeds up the matching process.

Troubleshooting

If you have rewritten the query to remove the function but are still seeing performance issues or unexpected results, start by checking the Statistics of the table. Outdated statistics can lead the optimizer to choose a scan over a seek even if the query is SARGable. Run UPDATE STATISTICS TableName to ensure the optimizer has the most current data distribution map.

If the error persists despite removing the function, check for Implicit Conversions. This happens when you compare two different data types (e.g., comparing a VARCHAR column to a NVARCHAR variable). SQL Server internally applies a conversion function to the column to make the types match, which triggers the same "function call" logic as an explicit function. Ensure your variable types exactly match your column types.

If you are unable to change the query because it is generated by a third-party application, your only recourse is the Persisted Computed Column mentioned in the Tips section. By creating a column that mirrors the function the application is using and indexing it, you provide the optimizer with a pre-calculated path to the data, which can often bypass the matching error.

Frequently Asked Questions

What does SARGable actually mean?

SARGable stands for Search ARGumentable. A query is SARGable if the SQL Server query optimizer can take advantage of an index to speed up the execution of the query. Using a function on a column in the WHERE clause makes the query non-SARGable.

Why does SQL Server care if I use a function in a JOIN?

When you wrap a column in a function, SQL Server cannot know the result of that function without executing it for every single row in the table. This turns an efficient "Seek" (jumping straight to the data) into a "Scan" (reading every single page of the table), which is devastating for performance on large datasets.

Can I use a function on the right side of the operator?

Yes. Using a function on a constant or a variable (the right side) is perfectly fine. For example, WHERE Column = LEFT(@Variable, 3) is SARGable because the function is calculated once for the variable, and then that single result is used to seek the index on the column.

Does this error happen with all functions?

It happens with any function that transforms the column value before the comparison. This includes scalar functions, system functions like GETDATE() (if used to transform a column), and user-defined functions (UDFs) used in the matching logic.

Will removing the function change my results?

If rewritten correctly, the results will be identical. However, you must be careful with trailing spaces, case sensitivity (depending on your collation), and NULL values, as LIKE and range comparisons may behave slightly differently than specific string functions.