SQL Server String Functions: Full List & Examples

Formulas & functions · Updated November 23, 2026

SQL Server string functions are built-in routines that let you manipulate character data—things like trimming spaces, extracting substrings, changing case, replacing text, and splitting or concatenating values. For example, LEFT('SQL Server', 3) returns 'SQL' and REPLACE('abc-abc', 'a', 'x') returns 'xbc-xbc'. These functions work on data types like varchar, nvarchar, char, and nchar, and they are essential for cleaning, transforming, and formatting text in queries and stored procedures.

What Are String Functions and Why Use Them?

String functions in SQL Server are part of the Transact-SQL (T-SQL) language. They accept one or more string inputs and return a string or a numeric value. You use them in SELECT statements, WHERE clauses, ORDER BY, and even in computed columns or views. Common real-world uses include:

  • Cleaning imported data (removing extra spaces, fixing inconsistent case).
  • Extracting parts of codes, like pulling the area code from a phone number.
  • Formatting output for reports, such as adding leading zeros.
  • Searching for patterns in text with LIKE or CHARINDEX.

Without these functions, you would have to write complex loops or use client-side code to perform even simple text manipulations.

Core String Functions: The Essential List

SQL Server provides over 50 string functions. Here are the most commonly used ones, grouped by what they do.

Extract and Count

  • LEFT(string, n) – returns the leftmost n characters. Example: LEFT('Database', 4) → 'Data'.
  • RIGHT(string, n) – returns the rightmost n characters. Example: RIGHT('Database', 4) → 'base'.
  • SUBSTRING(string, start, length) – returns a part starting at position start (1-based) for length characters. Example: SUBSTRING('SQL Server', 5, 3) → 'Ser'.
  • LEN(string) – returns the number of characters (excluding trailing spaces). Example: LEN('Hello ') → 5.
  • CHARINDEX(substring, string) – returns the starting position of the first occurrence, or 0 if not found. Example: CHARINDEX('er', 'Server') → 3.
  • PATINDEX('%pattern%', string) – returns the starting position of a pattern using wildcards. Example: PATINDEX('%[0-9]%', 'abc123') → 4.

Modify and Transform

  • REPLACE(string, old, new) – replaces all occurrences of old with new. Example: REPLACE('red-green', '-', '/') → 'red/green'.
  • STUFF(string, start, length, new) – deletes length characters from start and inserts new there. Example: STUFF('abcdef', 2, 3, 'XYZ') → 'aXYZef'.
  • LOWER(string) and UPPER(string) – convert to lowercase or uppercase. Example: UPPER('sql') → 'SQL'.
  • LTRIM(string), RTRIM(string), and TRIM(string) – remove leading, trailing, or both spaces. In SQL Server 2017+, TRIM can also remove other characters: TRIM('.' FROM '.abc.') → 'abc'.
  • CONCAT(string1, string2, ...) – joins strings, treating NULL as empty string. Example: CONCAT('a', NULL, 'b') → 'ab'.
  • STRING_AGG(column, delimiter) – concatenates values from multiple rows into one string (SQL Server 2017+). Example: STRING_AGG(Name, ', ') → 'Alice, Bob, Carol'.

Split and Format

  • STRING_SPLIT(string, delimiter) – splits a string into rows (SQL Server 2016+). Example: SELECT value FROM STRING_SPLIT('a,b,c', ',') returns three rows.
  • FORMAT(value, format) – formats dates and numbers using .NET format strings. Example: FORMAT(GETDATE(), 'yyyy-MM-dd') → '2025-03-14'.
  • REPLICATE(string, n) – repeats a string n times. Example: REPLICATE('0', 3) → '000'.
  • SPACE(n) – returns a string of n spaces.

How to Use String Functions in Queries

You can use string functions directly in a SELECT list or inside a WHERE clause. For example, to find all customers whose last name starts with ‘Smi’ and display the first three letters of their first name:

SELECT LEFT(FirstName, 3) AS ShortName
FROM Customers
WHERE LastName LIKE 'Smi%';

You can also use them in ORDER BY to sort by a transformed value. Keep in mind that using a function in a WHERE clause can prevent the query optimizer from using an index on that column, which may slow down large tables. In such cases, consider a computed column or a different approach.

Common Pitfalls and How to Avoid Them

String functions often produce unexpected results when you don’t account for data types and NULLs.

  • Trailing spaces: LEN ignores trailing spaces, but DATALENGTH counts bytes. If you need the true length including spaces, use DATALENGTH(string) for varchar (but note it returns bytes, not characters, for nvarchar).
  • NULL handling: Most string functions return NULL if any input is NULL. For example, LEFT(NULL, 3) returns NULL. Use ISNULL or COALESCE to provide defaults.
  • Unicode vs. non-Unicode: Functions like LEN count characters, but DATALENGTH counts bytes. For nvarchar, each character is 2 bytes. If you mix data types, implicit conversions can cause performance issues.
  • Collation: String comparisons and functions like UPPER are affected by collation, which defines case sensitivity and accent sensitivity. For case-insensitive collations, UPPER works as expected, but for case-sensitive ones, you must be explicit.

Choosing the Right Function: A Decision Guide

When you need to manipulate strings, think about what you want to do:

  • Need a fixed number of characters from the start or end? Use LEFT or RIGHT.
  • Need a middle portion? Use SUBSTRING.
  • Need to find a position? Use CHARINDEX or PATINDEX.
  • Need to replace or delete and insert? Use REPLACE or STUFF.
  • Need to combine values from multiple rows? Use STRING_AGG (2017+) or the older FOR XML PATH method.
  • Need to split a delimited string? Use STRING_SPLIT (2016+).

For older versions (before 2016), you may need to write custom split functions or use XML methods. Always test with your SQL Server version because some functions are version-specific.

Performance Considerations and Best Practices

String functions are generally fast, but they can slow down queries when used on large tables or in WHERE clauses. Here are some tips:

  • Avoid applying functions to columns in WHERE clauses if possible. Instead, store pre-computed values or use a computed column with an index.
  • When using LIKE with leading wildcards (e.g., '%abc'), the query cannot use an index. Consider full-text search for large text searches.
  • Use CONCAT instead of the + operator to handle NULLs gracefully. The + operator returns NULL if any operand is NULL.
  • For large string manipulations, consider using STUFF instead of multiple REPLACE calls, as it may be more efficient.
  • Be aware of the STRING_SPLIT output order: it does not guarantee order unless you include an ordinal column (available in SQL Server 2022+ with enable_ordinal).

Frequently Asked Questions

What is the difference between LEN and DATALENGTH?

LEN returns the number of characters in a string, ignoring trailing spaces. DATALENGTH returns the number of bytes used to store the string. For varchar, each character is 1 byte, so DATALENGTH equals the number of characters (including trailing spaces). For nvarchar, each character is 2 bytes, so DATALENGTH is double the character count. Use LEN when you need the logical length, and DATALENGTH when you need storage size.

How do I concatenate strings with NULL values?

Using the + operator, if any string is NULL, the result is NULL. To treat NULL as an empty string, use CONCAT, which automatically converts NULLs to empty strings. For example, CONCAT('a', NULL, 'b') returns 'ab'. Alternatively, use ISNULL(column, '') before concatenating.

Can I use string functions in a WHERE clause?

Yes, you can use them in a WHERE clause, but be aware that applying a function to a column often prevents the query optimizer from using an index on that column. For example, WHERE UPPER(LastName) = 'SMITH' will not use an index on LastName unless you create a computed column. If performance is critical, consider storing the transformed value in a separate column.

Is there a function to split a string into multiple columns?

SQL Server does not have a built-in function to split a string into columns directly. STRING_SPLIT splits into rows, not columns. To split into columns, you can use PARSENAME for simple dot-separated strings or use SUBSTRING with CHARINDEX for fixed patterns. For more complex splits, you may need to use a custom function or a JSON/XML approach.

What is the difference between CHARINDEX and PATINDEX?

CHARINDEX searches for an exact substring and returns its starting position. PATINDEX searches for a pattern using wildcards (like % and _) and returns the starting position of the first match. For example, CHARINDEX('er', 'Server') returns 3, while PATINDEX('%[0-9]%', 'abc123') returns 4 because the first digit is at position 4.

How do I remove all non-numeric characters from a string?

There is no single built-in function, but you can use a combination of PATINDEX and STUFF in a loop or use a recursive CTE. A common trick is to use REPLACE with a pattern, but that only removes one character at a time. For a robust solution, you can use a user-defined function or a numbers table to rebuild the string. In SQL Server 2022, you can use TRANSLATE to replace multiple characters, but it does not remove them.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.