Smart Systems for Home

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

Microsoft SQL String Functions: A How-To Guide

· 5 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

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

  1. 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.
  2. Start with concatenation. Use the + operator or the CONCAT function to join strings. For example: SELECT 'Hello' + ' ' + 'World'; returns Hello World. CONCAT treats NULL as an empty string, while + returns NULL if any operand is NULL.
  3. Measure string length with LEN (trailing spaces are ignored) or DATALENGTH (returns bytes, including trailing spaces). Example: SELECT LEN('SQL Server'); returns 10.
  4. Extract substrings using SUBSTRING. Syntax: SUBSTRING(expression, start, length). Example: SELECT SUBSTRING('Microsoft SQL', 1, 9); returns Microsoft. Note that start is 1-based.
  5. Find the position of a substring with CHARINDEX. Example: SELECT CHARINDEX('SQL', 'Microsoft SQL Server'); returns 11. If not found, it returns 0.
  6. Replace text using REPLACE. Syntax: REPLACE(string, old, new). Example: SELECT REPLACE('Hello World', 'World', 'SQL'); returns Hello SQL.
  7. Remove leading and trailing spaces with LTRIM and RTRIM, or TRIM (available in SQL Server 2017 and later) to remove both. Example: SELECT TRIM(' text '); returns text.
  8. Change case using UPPER and LOWER. Example: SELECT UPPER('sql'); returns SQL.
  9. Pad strings with LEFT and RIGHT combined with REPLICATE, or use FORMAT for numeric padding. For simple left-padding: SELECT RIGHT('00000' + '123', 5); returns 00123.
  10. Reverse a string with REVERSE. Example: SELECT REVERSE('abc'); returns cba.
  11. 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.
  12. 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.
  13. 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: SUBSTRING and CHARINDEX use 1-based positions. Starting at 0 returns an empty string or unexpected results.
  • Forgetting NULL propagation: Using + with a NULL operand yields NULL. Use CONCAT or ISNULL/COALESCE to handle NULLs gracefully.
  • Confusing LEN and DATALENGTH: LEN ignores trailing spaces, while DATALENGTH counts bytes. Use DATALENGTH for binary or to include trailing spaces.
  • Using TRIM on older versions: TRIM was introduced in SQL Server 2017. On older versions, use LTRIM(RTRIM(column)).
  • Overlooking collation: String comparisons and functions like CHARINDEX can 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 FORMAT for formatting numbers and dates as strings, but be aware it can be slower than CONVERT.
  • When working with large datasets, avoid applying functions to indexed columns in WHERE clauses if possible, as it can prevent index usage.
  • Use STRING_ESCAPE to 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, and STRING_AGG require SQL Server 2016 or later. Use SELECT @@VERSION; to verify.
  • Unexpected NULL results: Review your use of + and ensure you handle NULLs with ISNULL or COALESCE.
  • 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 COLLATE to 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.