SQL Server includes a comprehensive set of built-in string functions—over 30 in total—that let you manipulate, search, format, and analyze character data directly in T-SQL. These functions range from basic operations like LEN and SUBSTRING to advanced ones like STRING_AGG and TRANSLATE, and they are essential for cleaning data, building reports, and handling user input.
What Are String Functions in SQL Server?
String functions are built-in T-SQL functions that operate on an input string (or an expression that evaluates to a string) and return a string or numeric value. They are part of the SQL Server engine, meaning they are always available without any additional setup. These functions work with character data types: char, varchar, nchar, nvarchar, and sometimes text (though text is deprecated). They can be used in SELECT lists, WHERE clauses, ORDER BY, and even in computed columns.
Core String Functions Every User Should Know
Here are the most frequently used built-in string functions, grouped by what they do. All examples assume a table named Employees with a column FullName.
Length and Trimming
LEN(string)– Returns the number of characters in a string, excluding trailing spaces. Example:SELECT LEN('Hello ') -- returns 5.DATALENGTH(string)– Returns the number of bytes used, including trailing spaces. Useful forvarcharvsnvarchar.LTRIM(string)– Removes leading spaces.RTRIM(string)– Removes trailing spaces.TRIM(string)– Removes both leading and trailing spaces (SQL Server 2017+).
Substring and Splitting
SUBSTRING(string, start, length)– Extracts a portion of a string. Example:SUBSTRING('SQL Server', 5, 6) -- returns 'Server'.LEFT(string, number_of_chars)– Returns the left part.RIGHT(string, number_of_chars)– Returns the right part.STRING_SPLIT(string, separator)– Splits a string into rows based on a delimiter (SQL Server 2016+). Returns a single column namedvalue.
Search and Replace
CHARINDEX(substring, string)– Returns the starting position of the first occurrence, or 0 if not found. Example:CHARINDEX('er', 'Server') -- returns 4.PATINDEX('%pattern%', string)– Returns the position of a pattern using wildcards. Example:PATINDEX('%[0-9]%', 'abc123') -- returns 4.REPLACE(string, old, new)– Replaces all occurrences of a substring. Example:REPLACE('SQL', 'SQL', 'NoSQL') -- returns 'NoSQL'.STUFF(string, start, length, new_string)– Deletes a specified length and inserts another string at the start position.
Case and Formatting
UPPER(string)andLOWER(string)– Convert to uppercase or lowercase.CONCAT(string1, string2, ...)– Joins multiple strings, ignoring NULLs (SQL Server 2012+). Example:CONCAT('Hello', ' ', 'World').CONCAT_WS(separator, string1, string2, ...)– Concatenates with a separator (SQL Server 2017+).FORMAT(value, format_string)– Formats dates and numbers using .NET format strings, but it’s slower thanCONVERT.
Advanced and Aggregation
STRING_AGG(expression, separator)– Concatenates values from multiple rows into a single string (SQL Server 2017+). Example:SELECT STRING_AGG(FullName, ', ') FROM Employees.TRANSLATE(string, from_chars, to_chars)– Replaces each character infrom_charswith the corresponding character into_chars(SQL Server 2017+).REPLICATE(string, times)– Repeats a string a specified number of times.REVERSE(string)– Reverses the string.SPACE(number)– Returns a string of spaces.
How to Choose the Right String Function
Selecting the correct function depends on what you need to do:
- Need length? Use
LENfor characters,DATALENGTHfor bytes. - Need to extract part of a string? Use
SUBSTRINGwhen you know the position;LEFTorRIGHTfor edges. - Need to find a position? Use
CHARINDEXfor exact text,PATINDEXfor patterns. - Need to replace? Use
REPLACEfor simple swaps,STUFFfor insert/delete at a specific position. - Need to combine rows? Use
STRING_AGG(modern) orFOR XML PATH(older versions). - Need to split a string? Use
STRING_SPLIT(SQL Server 2016+) or a custom function for older versions.
Common Pitfalls and Misconceptions
One common mistake is assuming LEN counts trailing spaces—it does not. Another is using SUBSTRING with a start position of 0; SQL Server treats 0 as 1, which can cause off-by-one errors. Also, REPLACE is case-insensitive by default for the collation, but not always; if you need case-sensitive replacement, use a case-sensitive collation. Finally, STRING_SPLIT does not guarantee the order of output rows; if order matters, you need to include a row number or use a different method.
String Functions vs. Other Approaches
Sometimes string functions are not the best tool. For complex pattern matching, using LIKE with wildcards in a WHERE clause is simpler than extracting with SUBSTRING. For heavy text processing, consider full-text search for large documents. For formatting dates and numbers, CONVERT and CAST are faster than FORMAT because FORMAT uses .NET CLR and is significantly slower in loops. For concatenating values from multiple rows, STRING_AGG is the modern choice, but in SQL Server 2016 and earlier you might use FOR XML PATH or a recursive CTE.
Performance and Cost Considerations
String functions can impact performance, especially on large tables. Using functions in a WHERE clause often prevents index seeks, forcing scans. For example, WHERE LEN(LastName) > 5 cannot use an index on LastName. To improve performance, avoid applying functions to columns in predicates; instead, store computed values or use a full-text index. Also, FORMAT is notoriously slow; use CONVERT with style codes for date formatting. When using STRING_AGG, be mindful of the maximum varchar size (8000) or use nvarchar(max) to avoid truncation.
Frequently Asked Questions
How do I concatenate strings in SQL Server?
Use the + operator or the CONCAT function. The + operator returns NULL if any operand is NULL, while CONCAT treats NULL as an empty string. Example: SELECT FirstName + ' ' + LastName vs SELECT CONCAT(FirstName, ' ', LastName).
How do I check if a string contains a substring?
Use CHARINDEX or PATINDEX. For example, SELECT * FROM Employees WHERE CHARINDEX('Smith', FullName) > 0. You can also use LIKE '%Smith%', but CHARINDEX is often clearer for exact matches.
What is the difference between LEN and DATALENGTH?
LEN returns the number of characters, ignoring trailing spaces. DATALENGTH returns the number of bytes used, including trailing spaces. For varchar, each character is 1 byte; for nvarchar, each is 2 bytes. So LEN(N'abc') returns 3, but DATALENGTH(N'abc') returns 6.
How do I split a comma-separated string into rows?
In SQL Server 2016 and later, use STRING_SPLIT: SELECT value FROM STRING_SPLIT('apple,banana,cherry', ','). For older versions, you need a custom split function or use XML methods.
Why is my STRING_AGG result truncated?
STRING_AGG with a varchar column can be limited to 8000 characters. To avoid truncation, cast the column to varchar(max) or nvarchar(max) before aggregating: SELECT STRING_AGG(CAST(Column AS nvarchar(max)), ',').
Can I use string functions in a WHERE clause?
Yes, but be cautious about performance. Functions like UPPER or SUBSTRING in a WHERE clause can make the query non-sargable, preventing index usage. If you need case-insensitive search, use a case-insensitive collation instead of UPPER.
Related
- Amex Send & Split: How It Works, Limits, Fees
- Case When Count Distinct SQL: Syntax & Examples
- Selected Cell How Many Minutes Per Cycle? Answer
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Transpose in Excel and Keep Formulas: A Practical GuideTo transpose a range in Excel and keep its formulas, copy the cells, select a blank destination, then…
- Excel Workdays Between Dates: Formulas and ExamplesTo count workdays between two dates in Excel, use NETWORKDAYS. With the start date in A2 and the…
- Excel Formula to Check Whether a Value Is in a ListWith list items in A2:A10 and the value to check in D2, use =IF(COUNTIF($A$2:$A$10,D2)>0,"Found","Not found"). COUNTIF checks whether…
- HLOOKUP Examples in Excel: Formulas and Common FixesIn Excel, HLOOKUP searches across the first row of a range and returns a value from a specified…
- Excel INDEX Array Formula: How It Works and When to Use ItIn Excel for Microsoft 365, INDEX can return a value from a range or return an array of…
- Compare Two Columns in Excel with XLOOKUPTo check whether each value in column A appears anywhere in column B, enter =IF(ISNA(XLOOKUP(A2,$B$$2:$B$100,$B$2:$B$100,,0)),"Not found","Match") in C2…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.