SQL Server string functions are built-in routines that let you manipulate character data—things like trimming spaces, extracting substrings, changing case, replacing text, and splitting or concatenating values. For example, LEFT('SQL Server', 3) returns 'SQL' and REPLACE('abc-abc', 'a', 'x') returns 'xbc-xbc'. These functions work on data types like varchar, nvarchar, char, and nchar, and they are essential for cleaning, transforming, and formatting text in queries and stored procedures.
What Are String Functions and Why Use Them?
String functions in SQL Server are part of the Transact-SQL (T-SQL) language. They accept one or more string inputs and return a string or a numeric value. You use them in SELECT statements, WHERE clauses, ORDER BY, and even in computed columns or views. Common real-world uses include:
- Cleaning imported data (removing extra spaces, fixing inconsistent case).
- Extracting parts of codes, like pulling the area code from a phone number.
- Formatting output for reports, such as adding leading zeros.
- Searching for patterns in text with
LIKEorCHARINDEX.
Without these functions, you would have to write complex loops or use client-side code to perform even simple text manipulations.
Core String Functions: The Essential List
SQL Server provides over 50 string functions. Here are the most commonly used ones, grouped by what they do.
Extract and Count
LEFT(string, n)– returns the leftmostncharacters. Example:LEFT('Database', 4)→'Data'.RIGHT(string, n)– returns the rightmostncharacters. Example:RIGHT('Database', 4)→'base'.SUBSTRING(string, start, length)– returns a part starting at positionstart(1-based) forlengthcharacters. Example:SUBSTRING('SQL Server', 5, 3)→'Ser'.LEN(string)– returns the number of characters (excluding trailing spaces). Example:LEN('Hello ')→ 5.CHARINDEX(substring, string)– returns the starting position of the first occurrence, or 0 if not found. Example:CHARINDEX('er', 'Server')→ 3.PATINDEX('%pattern%', string)– returns the starting position of a pattern using wildcards. Example:PATINDEX('%[0-9]%', 'abc123')→ 4.
Modify and Transform
REPLACE(string, old, new)– replaces all occurrences ofoldwithnew. Example:REPLACE('red-green', '-', '/')→'red/green'.STUFF(string, start, length, new)– deleteslengthcharacters fromstartand insertsnewthere. Example:STUFF('abcdef', 2, 3, 'XYZ')→'aXYZef'.LOWER(string)andUPPER(string)– convert to lowercase or uppercase. Example:UPPER('sql')→'SQL'.LTRIM(string),RTRIM(string), andTRIM(string)– remove leading, trailing, or both spaces. In SQL Server 2017+,TRIMcan also remove other characters:TRIM('.' FROM '.abc.')→'abc'.CONCAT(string1, string2, ...)– joins strings, treating NULL as empty string. Example:CONCAT('a', NULL, 'b')→'ab'.STRING_AGG(column, delimiter)– concatenates values from multiple rows into one string (SQL Server 2017+). Example:STRING_AGG(Name, ', ')→'Alice, Bob, Carol'.
Split and Format
STRING_SPLIT(string, delimiter)– splits a string into rows (SQL Server 2016+). Example:SELECT value FROM STRING_SPLIT('a,b,c', ',')returns three rows.FORMAT(value, format)– formats dates and numbers using .NET format strings. Example:FORMAT(GETDATE(), 'yyyy-MM-dd')→'2025-03-14'.REPLICATE(string, n)– repeats a stringntimes. Example:REPLICATE('0', 3)→'000'.SPACE(n)– returns a string ofnspaces.
How to Use String Functions in Queries
You can use string functions directly in a SELECT list or inside a WHERE clause. For example, to find all customers whose last name starts with ‘Smi’ and display the first three letters of their first name:
SELECT LEFT(FirstName, 3) AS ShortName
FROM Customers
WHERE LastName LIKE 'Smi%';
You can also use them in ORDER BY to sort by a transformed value. Keep in mind that using a function in a WHERE clause can prevent the query optimizer from using an index on that column, which may slow down large tables. In such cases, consider a computed column or a different approach.
Common Pitfalls and How to Avoid Them
String functions often produce unexpected results when you don’t account for data types and NULLs.
- Trailing spaces:
LENignores trailing spaces, butDATALENGTHcounts bytes. If you need the true length including spaces, useDATALENGTH(string)for varchar (but note it returns bytes, not characters, for nvarchar). - NULL handling: Most string functions return NULL if any input is NULL. For example,
LEFT(NULL, 3)returns NULL. UseISNULLorCOALESCEto provide defaults. - Unicode vs. non-Unicode: Functions like
LENcount characters, butDATALENGTHcounts bytes. Fornvarchar, each character is 2 bytes. If you mix data types, implicit conversions can cause performance issues. - Collation: String comparisons and functions like
UPPERare affected by collation, which defines case sensitivity and accent sensitivity. For case-insensitive collations,UPPERworks as expected, but for case-sensitive ones, you must be explicit.
Choosing the Right Function: A Decision Guide
When you need to manipulate strings, think about what you want to do:
- Need a fixed number of characters from the start or end? Use
LEFTorRIGHT. - Need a middle portion? Use
SUBSTRING. - Need to find a position? Use
CHARINDEXorPATINDEX. - Need to replace or delete and insert? Use
REPLACEorSTUFF. - Need to combine values from multiple rows? Use
STRING_AGG(2017+) or the olderFOR XML PATHmethod. - Need to split a delimited string? Use
STRING_SPLIT(2016+).
For older versions (before 2016), you may need to write custom split functions or use XML methods. Always test with your SQL Server version because some functions are version-specific.
Performance Considerations and Best Practices
String functions are generally fast, but they can slow down queries when used on large tables or in WHERE clauses. Here are some tips:
- Avoid applying functions to columns in
WHEREclauses if possible. Instead, store pre-computed values or use a computed column with an index. - When using
LIKEwith leading wildcards (e.g.,'%abc'), the query cannot use an index. Consider full-text search for large text searches. - Use
CONCATinstead of the+operator to handle NULLs gracefully. The+operator returns NULL if any operand is NULL. - For large string manipulations, consider using
STUFFinstead of multipleREPLACEcalls, as it may be more efficient. - Be aware of the
STRING_SPLIToutput order: it does not guarantee order unless you include an ordinal column (available in SQL Server 2022+ withenable_ordinal).
Frequently Asked Questions
What is the difference between LEN and DATALENGTH?
LEN returns the number of characters in a string, ignoring trailing spaces. DATALENGTH returns the number of bytes used to store the string. For varchar, each character is 1 byte, so DATALENGTH equals the number of characters (including trailing spaces). For nvarchar, each character is 2 bytes, so DATALENGTH is double the character count. Use LEN when you need the logical length, and DATALENGTH when you need storage size.
How do I concatenate strings with NULL values?
Using the + operator, if any string is NULL, the result is NULL. To treat NULL as an empty string, use CONCAT, which automatically converts NULLs to empty strings. For example, CONCAT('a', NULL, 'b') returns 'ab'. Alternatively, use ISNULL(column, '') before concatenating.
Can I use string functions in a WHERE clause?
Yes, you can use them in a WHERE clause, but be aware that applying a function to a column often prevents the query optimizer from using an index on that column. For example, WHERE UPPER(LastName) = 'SMITH' will not use an index on LastName unless you create a computed column. If performance is critical, consider storing the transformed value in a separate column.
Is there a function to split a string into multiple columns?
SQL Server does not have a built-in function to split a string into columns directly. STRING_SPLIT splits into rows, not columns. To split into columns, you can use PARSENAME for simple dot-separated strings or use SUBSTRING with CHARINDEX for fixed patterns. For more complex splits, you may need to use a custom function or a JSON/XML approach.
What is the difference between CHARINDEX and PATINDEX?
CHARINDEX searches for an exact substring and returns its starting position. PATINDEX searches for a pattern using wildcards (like % and _) and returns the starting position of the first match. For example, CHARINDEX('er', 'Server') returns 3, while PATINDEX('%[0-9]%', 'abc123') returns 4 because the first digit is at position 4.
How do I remove all non-numeric characters from a string?
There is no single built-in function, but you can use a combination of PATINDEX and STUFF in a loop or use a recursive CTE. A common trick is to use REPLACE with a pattern, but that only removes one character at a time. For a robust solution, you can use a user-defined function or a numbers table to rebuild the string. In SQL Server 2022, you can use TRANSLATE to replace multiple characters, but it does not remove them.
Related
- Refresh PivotTable Data? How to Update in Excel
- Traffic Light Print Out: What It Is & How to Read It
- How to Change Camera View in Blender (Orbit, Zoom, Pan)
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Filter Shortcut: Turn AutoFilter On or OffIn Excel for Microsoft 365 on Windows, press Ctrl+Shift+L to turn AutoFilter on or off for the current…
- Remove Filter From an Excel Table: Steps and OptionsTo remove the filter arrows from an Excel table in Microsoft 365 for Windows, click a cell in…
- Power Query Sort: How to Sort and Keep Rows in OrderTo sort data in Power Query in Excel for Microsoft 365 on Windows, open the query, select the…
- Excel Loan Payment Formula: How to Use PMTFor a fixed-rate loan with monthly payments, Excel’s PMT function calculates the regular payment. If B1 contains the…
- Excel Concatenate Dates While Keeping Formatting in TextTo concatenate a date in Excel and keep its display format, convert the date to formatted text with…
- How to Copy a Formula Down All Rows in ExcelTo copy a formula down a column in Excel, enter it in the first cell, select the cells…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.