SQL Server provides over 30 built-in string functions that let you manipulate text data directly in T-SQL, covering tasks like trimming, splitting, searching, replacing, and formatting. This guide explains the most useful ones, how they work, and when to use them, with clear examples for each.
Why String Functions Matter
Text data is everywhere in databases—names, addresses, product codes, log messages. Without string functions, you’d have to pull raw data into an application and process it there, which adds network overhead and complexity. SQL Server’s string functions let you clean, transform, and extract information directly in queries, making reports and integrations faster and simpler. They are essential for tasks like standardizing customer names, parsing URLs, or generating formatted output.
Core String Functions You’ll Use Daily
These are the workhorses: LEN, SUBSTRING, LEFT, RIGHT, CHARINDEX, REPLACE, UPPER, LOWER, and TRIM. Here’s what each does:
LEN(string)returns the number of characters, excluding trailing spaces. For example,LEN('Hello ')returns 5.SUBSTRING(string, start, length)extracts a part.SUBSTRING('abcdef', 2, 3)gives ‘bcd’.LEFT(string, n)andRIGHT(string, n)take the first or last n characters.CHARINDEX(substring, string)finds the starting position of a substring (1-based). Returns 0 if not found.REPLACE(string, old, new)swaps all occurrences.UPPERandLOWERchange case.TRIM(string)removes leading and trailing spaces (and optionally other characters).
Example: To get the first name from a full name in column FullName (assuming a space separator):
SELECT LEFT(FullName, CHARINDEX(' ', FullName + ' ') - 1) AS FirstName FROM Users;
The + ' ' trick handles names without a space, avoiding a NULL result.
Advanced Functions for Complex Text Handling
Newer versions of SQL Server added powerful functions that simplify tasks that previously required complex loops or user-defined functions.
STRING_SPLIT(SQL Server 2016+) splits a string into rows based on a delimiter. Example:SELECT value FROM STRING_SPLIT('apple,banana,cherry', ',');returns three rows.STRING_AGG(SQL Server 2017+) concatenates values from multiple rows into a single string. Example:SELECT STRING_AGG(Name, ', ') FROM Students;CONCATandCONCAT_WS(2012+) safely join strings, treating NULLs as empty strings.CONCAT_WS(', ', FirstName, LastName)adds a separator between non-null values.FORMAT(2012+) formats dates and numbers using .NET format strings, e.g.,FORMAT(GETDATE(), 'yyyy-MM-dd').TRANSLATE(2017+) replaces multiple single characters in one call, likeTRANSLATE('abc', 'ab', 'xy')returns ‘xyc’.
Note: STRING_SPLIT does not guarantee output order without an ORDINAL column (available in Azure SQL Database and SQL Server 2022).
How to Choose the Right Function
Picking the right function depends on your goal:
- Extract a fixed number of characters: Use
LEFT,RIGHT, orSUBSTRING. - Find a position: Use
CHARINDEXorPATINDEX(which supports wildcards). - Remove or replace text: Use
REPLACEorTRANSLATE. - Split into rows: Use
STRING_SPLIT. - Combine rows into one string: Use
STRING_AGG. - Clean up spaces: Use
TRIM,LTRIM, orRTRIM.
For pattern-based searching, PATINDEX returns the position of a pattern, e.g., PATINDEX('%[0-9]%', 'abc123') returns 4.
Common Pitfalls and How to Avoid Them
String functions can behave unexpectedly if you don’t watch out for these issues:
- Trailing spaces:
LENignores trailing spaces, butDATALENGTHcounts bytes. UseDATALENGTHto get exact byte length. - NULL handling: Most functions return NULL if any argument is NULL. Use
ISNULLorCOALESCEto provide defaults. - Collation: Case sensitivity depends on the database collation. In a case-insensitive collation (e.g.,
SQL_Latin1_General_CP1_CI_AS),CHARINDEXwill match ‘A’ and ‘a’ alike. To force case-sensitive, use a case-sensitive collation or specify it in the function. - Performance: Using functions on columns in a WHERE clause (e.g.,
WHERE UPPER(Name) = 'JOHN') prevents index usage. Instead, store data in a consistent case or use a computed column. - Unicode vs. non-Unicode:
LENcounts characters, not bytes. For Unicode data,DATALENGTHreturns twice the number of characters.
Example of a common mistake: SELECT LEN(' hello ') returns 5, not 7, because trailing spaces are ignored. Use TRIM first to get the trimmed length.
String Functions vs. LIKE and Full-Text Search
String functions are for precise manipulation, not searching. The LIKE operator is better for pattern matching in WHERE clauses, e.g., WHERE Name LIKE 'A%'. However, LIKE with a leading wildcard (e.g., '%son') can’t use an index. For large text columns, consider Full-Text Search (FTS) which supports word-based queries and ranking. String functions are not designed for that; they operate on the whole string value.
Performance Considerations
String functions are generally fast, but they can be slow if used carelessly:
- Avoid applying functions to columns in JOIN or WHERE clauses—this forces a scan.
- Use
STRING_SPLITinstead of custom split loops; it’s optimized. - Be mindful of large strings:
REPLACEon a 10MB string can be memory-intensive. - For repeated transformations, consider a computed column or a persisted computed column with an index.
Example of a bad pattern: SELECT * FROM Orders WHERE SUBSTRING(OrderCode, 1, 3) = 'ABC'; This prevents index usage. Better to store the prefix separately or use a computed column.
Frequently Asked Questions
How do I split a string into multiple columns?
Use STRING_SPLIT to get rows, then pivot with PIVOT or conditional aggregation. For a fixed number of parts, you can use CHARINDEX and SUBSTRING to extract each piece. Example to get the first three comma-separated values: use SUBSTRING with CHARINDEX to find positions.
What’s the difference between CHARINDEX and PATINDEX?
CHARINDEX looks for an exact substring and returns its starting position. PATINDEX uses wildcard patterns (like % and _) and returns the position of the first match. For example, PATINDEX('%[0-9]%', 'abc123') returns 4, while CHARINDEX('1', 'abc123') returns 4 as well, but PATINDEX can find any digit.
Can I use string functions in a GROUP BY or ORDER BY?
Yes, you can use string functions in ORDER BY and GROUP BY, but be aware of performance. For example, ORDER BY LEN(Name) works, but it may be slow on large tables. In GROUP BY, you can group by the result of a function, like GROUP BY UPPER(Country), but that again prevents index usage.
How do I remove all non-alphanumeric characters?
There’s no built-in function, but you can use a recursive CTE or a numbers table to iterate through characters. A simpler approach is to use TRANSLATE to replace unwanted characters, but you’d need to list them all. For a robust solution, consider a user-defined function that loops through the string.
Is there a function to reverse a string?
Yes, REVERSE(string) returns the string in reverse order. For example, REVERSE('abc') returns ‘cba’. This is useful for checking palindromes or reversing date strings.
Why does LEN ignore trailing spaces?
By design, LEN returns the number of characters excluding trailing spaces. This is because trailing spaces are often insignificant in data. If you need the full length including spaces, use DATALENGTH(string) and divide by 2 for Unicode (or use DATALENGTH directly for varchar).
Related
- Select All Windows Command: Full Guide
- Counter Object Python: How It Works & When to Use It
- Google Sheets Count Checkbox: 4 Easy Ways
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Let Cell Overflow? How to Show Text Across CellsYes. In Excel for Microsoft 365 on Windows, text can overflow into the cells to its right when…
- Databricks SQL Functions: Types, Examples, and UsageDatabricks SQL functions are built-in or user-defined operations you call from SQL to transform values, summarize rows, work…
- Excel Sort Examples: Rows, Text, Dates, and Custom ListsTo sort a worksheet in Excel for Microsoft 365 on Windows, select a cell in the data, then…
- Excel Formula for NPV: How to Use ItThe Excel formula for net present value (NPV) is =NPV(rate, value1, [value2], ...). For example, if your discount…
- Excel COUNTIF and SUMIF Examples That Actually WorkIn Excel, use COUNTIF(range, criteria) to count cells that meet one condition and SUMIF(range, criteria, sum_range) to add…
- How to Filter Highlighted Cells in Excel by Cell ColorTo filter highlighted cells in Excel, turn on filtering, open the drop-down arrow in the column that contains…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.