SQL Server String Functions: A How-To Guide
In this article
Microsoft SQL Server string functions let you clean, split, search, and reshape text directly in T-SQL, so you can fix messy data or build reports without exporting to Excel. The core set is built into every supported version: LEN, CHARINDEX, SUBSTRING, LEFT, RIGHT, REPLACE, UPPER, LOWER, LTRIM, RTRIM, CONCAT, and STRING_SPLIT. You can practice on any database you can query; no special setup is required beyond a connection and a table or literal values to test against.
What You'll Need
- Access to a SQL Server instance (any recent version) and a tool such as SQL Server Management Studio (SSMS) or Azure Data Studio.
- A database where you have permission to run SELECT queries. You do not need to create tables to experiment; you can use literal strings like
SELECT LEN('hello'). - Basic familiarity with SELECT and WHERE clauses. If you are new to SQL, run the examples on a test database first, not production.
Step-by-Step
- Open a query window. In SSMS, connect to your instance and click New Query. In Azure Data Studio, open a new query tab. Menu labels can differ slightly by version, but the New Query action is in the same place in both tools.
- Test with literal strings first. Run
SELECT LEN('SQL Server') AS LenTest, UPPER('sql') AS UpperTest;to confirm your connection works and to see how functions return values. This avoids confusion between data issues and query issues. - Measure length and find positions. Use
LENto count characters (it ignores trailing spaces) andDATALENGTHwhen you need byte size. UseCHARINDEX('needle', 'haystack')to find where a substring starts; it returns 0 when not found. Example:SELECT CHARINDEX('Server', 'SQL Server') AS Pos;returns 5. - Extract parts of a string.
SUBSTRING(value, start, length)pulls a slice;LEFTandRIGHTtake from the ends. To get the first three characters:SELECT LEFT('abcdef', 3);returns 'abc'. To get characters 2 through 4:SELECT SUBSTRING('abcdef', 2, 3);returns 'bcd'. - Clean whitespace and case.
LTRIMandRTRIMremove leading and trailing spaces;TRIMremoves both in newer versions.UPPERandLOWERchange case. Example:SELECT TRIM(' hello ');returns 'hello'. Use these before comparing values so 'Yes' and 'yes ' match. - Replace and concatenate.
REPLACE(value, old, new)swaps text;CONCATjoins values and treats NULL as an empty string. Example:SELECT CONCAT('Hello', ' ', 'World');returns 'Hello World'. To remove dashes from a phone number:SELECT REPLACE('555-1234', '-', '');returns '5551234'. - Split delimited text.
STRING_SPLIT('a,b,c', ',')returns one row per value. Use it in a FROM clause:SELECT value FROM STRING_SPLIT('red,green,blue', ',');. This is useful for turning a comma-separated list into rows you can join or filter. - Apply functions to table columns. Once the literals behave as expected, use the same functions on columns. For example, to list cleaned email addresses:
SELECT LOWER(TRIM(Email)) AS CleanEmail FROM Customers;. Run a small SELECT first to check results before updating any data. - Combine functions for real cleanup. Nest calls to solve common problems. To extract the domain from an email:
SELECT SUBSTRING(Email, CHARINDEX('@', Email) + 1, LEN(Email)) AS Domain FROM Customers;. Test on a few rows, then expand. - Update data safely. If you need to persist changes, write an UPDATE with the same expression, but first run the SELECT version and check the row count. Back up or copy the table before bulk updates, and wrap the change in a transaction so you can roll back if the results look wrong.
Common Mistakes
- Assuming LEN counts trailing spaces. It does not. Use
DATALENGTHif you need the stored byte count, and remember it returns bytes, not characters, for some data types. - Forgetting that CHARINDEX returns 0 when not found. Adding 1 to that 0 can produce unexpected substrings. Check for 0 before using the result in SUBSTRING.
- Using + for concatenation with NULLs. If any value is NULL, the whole result becomes NULL. Use
CONCATorCONCAT_WSwhen NULLs are possible. - Ignoring data types. Functions like LEN expect a string; passing a number may cause implicit conversion. Cast explicitly with
CASTorCONVERTwhen mixing types. - Running UPDATE without a WHERE or a test SELECT. Always preview the affected rows first, and use a transaction for changes you might need to undo.
Tips
- Use
CONCAT_WSto join values with a separator while skipping NULLs, which is cleaner than manual separators. - For case-insensitive comparisons, SQL Server's default collation often handles it, but explicit
UPPERorLOWERmakes intent clear. - Keep expressions readable by breaking long nested calls across lines; the query optimizer does not care about formatting, but the next person reading it will.
- Test
STRING_SPLIToutput order carefully: it does not guarantee row order, so add an ORDER BY on a stable column if order matters. - When cleaning imported data, run a SELECT that shows both the original and cleaned value side by side before updating.
Troubleshooting
If a function returns an error, check the argument count and types first: SUBSTRING needs three arguments, REPLACE needs three, and CHARINDEX needs two. If you see NULL where you expected text, look for a NULL input or a failed conversion. If results look truncated, confirm the column's data type and length; a VARCHAR(10) column silently cuts longer values. If STRING_SPLIT is not recognized, your database compatibility level may be too low; check with your administrator before changing it. If an UPDATE affects more rows than expected, roll back the transaction immediately and re-run the SELECT version to inspect the data. When in doubt, work on a copy of the table.
Frequently Asked Questions
What is the difference between LEN and DATALENGTH?
LEN returns the number of characters excluding trailing spaces. DATALENGTH returns the number of bytes used, which can differ for Unicode types like NVARCHAR.
Can I use string functions in a WHERE clause?
Yes. For example, WHERE LOWER(Email) = 'a@b.com' works, but applying functions to columns can prevent index use, so test performance on large tables.
How do I remove only leading or only trailing spaces?
Use LTRIM for leading spaces and RTRIM for trailing spaces. TRIM removes both and is available in newer SQL Server versions.
Does STRING_SPLIT preserve the original order?
No. It returns rows without a guaranteed order. If order matters, include a sort key in your data or handle ordering in the application.
Why does CONCAT return a value when + returns NULL?
CONCAT treats NULL as an empty string, while the + operator returns NULL if any operand is NULL. Choose based on whether missing values should blank out the result.
Can I nest string functions?
Yes, nesting is common, such as SUBSTRING inside CHARINDEX. Keep nesting shallow for readability and test each layer separately when debugging.