Microsoft SQL String Functions: A How-To Guide
In this article
Microsoft SQL Server provides a set of built-in string functions that let you manipulate text directly in queries—concatenating, extracting, replacing, trimming, and measuring strings. To use them, you need access to a SQL Server instance (any recent version) and a tool like SQL Server Management Studio (SSMS) or Azure Data Studio. No special setup is required beyond a connection and a database where you can run queries.
What You'll Need
- A connection to a SQL Server database (local or remote) with permission to run SELECT queries.
- A query editor such as SSMS, Azure Data Studio, or the query window in Visual Studio.
- Basic familiarity with T-SQL SELECT statements.
Step-by-Step
- Open your query tool and connect to the database where you want to experiment. You can use any database; string functions work on literal values or column data.
- Start with concatenation. Use the
+operator or theCONCATfunction to join strings. For example:SELECT 'Hello' + ' ' + 'World';returns Hello World.CONCATtreats NULL as an empty string, while+returns NULL if any operand is NULL. - Measure string length with
LEN(trailing spaces are ignored) orDATALENGTH(returns bytes, including trailing spaces). Example:SELECT LEN('SQL Server');returns 10. - Extract substrings using
SUBSTRING. Syntax:SUBSTRING(expression, start, length). Example:SELECT SUBSTRING('Microsoft SQL', 1, 9);returns Microsoft. Note that start is 1-based. - Find the position of a substring with
CHARINDEX. Example:SELECT CHARINDEX('SQL', 'Microsoft SQL Server');returns 11. If not found, it returns 0. - Replace text using
REPLACE. Syntax:REPLACE(string, old, new). Example:SELECT REPLACE('Hello World', 'World', 'SQL');returns Hello SQL. - Remove leading and trailing spaces with
LTRIMandRTRIM, orTRIM(available in SQL Server 2017 and later) to remove both. Example:SELECT TRIM(' text ');returns text. - Change case using
UPPERandLOWER. Example:SELECT UPPER('sql');returns SQL. - Pad strings with
LEFTandRIGHTcombined withREPLICATE, or useFORMATfor numeric padding. For simple left-padding:SELECT RIGHT('00000' + '123', 5);returns 00123. - Reverse a string with
REVERSE. Example:SELECT REVERSE('abc');returns cba. - Split delimited strings using
STRING_SPLIT(SQL Server 2016 and later). Example:SELECT value FROM STRING_SPLIT('a,b,c', ',');returns three rows: a, b, c. - Combine rows into a single string with
STRING_AGG(SQL Server 2017 and later). Example:SELECT STRING_AGG(name, ', ') FROM sys.databases;returns a comma-separated list of database names. - Test your expressions by running SELECT statements with literal values before applying them to table columns. This helps you understand behavior with NULLs, empty strings, and special characters.
Common Mistakes
- Assuming 0-based indexing:
SUBSTRINGandCHARINDEXuse 1-based positions. Starting at 0 returns an empty string or unexpected results. - Forgetting NULL propagation: Using
+with a NULL operand yields NULL. UseCONCATorISNULL/COALESCEto handle NULLs gracefully. - Confusing LEN and DATALENGTH:
LENignores trailing spaces, whileDATALENGTHcounts bytes. UseDATALENGTHfor binary or to include trailing spaces. - Using TRIM on older versions:
TRIMwas introduced in SQL Server 2017. On older versions, useLTRIM(RTRIM(column)). - Overlooking collation: String comparisons and functions like
CHARINDEXcan be case-sensitive or accent-sensitive depending on collation. Test with your database's collation.
Tips
- Use
CONCAT_WS(SQL Server 2017+) to concatenate with a separator and skip NULLs automatically. - For complex string manipulation, consider
FORMATfor formatting numbers and dates as strings, but be aware it can be slower thanCONVERT. - When working with large datasets, avoid applying functions to indexed columns in WHERE clauses if possible, as it can prevent index usage.
- Use
STRING_ESCAPEto escape special characters like single quotes in dynamic SQL or output. - Always test string functions with edge cases: empty strings, NULLs, Unicode characters, and strings longer than expected.
Troubleshooting
- Function not recognized: Check your SQL Server version. Functions like
TRIM,STRING_SPLIT, andSTRING_AGGrequire SQL Server 2016 or later. UseSELECT @@VERSION;to verify. - Unexpected NULL results: Review your use of
+and ensure you handle NULLs withISNULLorCOALESCE. - Wrong substring extracted: Double-check start and length parameters. Remember that start is 1-based and length cannot exceed the remaining characters.
- Performance issues: If queries with string functions run slowly, check execution plans. Consider persisting computed columns or using full-text search for pattern matching.
- Collation conflicts: When combining strings from different databases with different collations, you may need to add
COLLATEto resolve conflicts.
Frequently Asked Questions
What is the difference between LEN and DATALENGTH?
LEN returns the number of characters in a string, excluding trailing spaces. DATALENGTH returns the number of bytes used to represent the string, including trailing spaces and for Unicode data, two bytes per character.
Can I use string functions on columns with NULL values?
Yes, but most functions return NULL if the input is NULL. Use ISNULL or COALESCE to provide a default value before applying the function.
How do I split a comma-separated string into rows?
Use STRING_SPLIT (SQL Server 2016+). Example: SELECT value FROM STRING_SPLIT('a,b,c', ',');. For older versions, you can use a custom split function or XML methods.
What is the difference between CHARINDEX and PATINDEX?
CHARINDEX searches for a substring and returns its starting position. PATINDEX searches for a pattern using wildcards and returns the starting position. Both return 0 if not found.
How can I remove all spaces from a string?
Use REPLACE(column, ' ', '') to remove all spaces, or TRIM to remove only leading and trailing spaces.
Is there a function to reverse a string?
Yes, use REVERSE(expression). It returns the string with characters in reverse order.