STUFF() in SQL
Deletes a specified length of characters and inserts another string at a specified start position in a string.
Syntax
Return type
STUFF() Function Example
What is STUFF() in SQL?
The STUFF()
function in SQL is used to delete a specified number of characters from a string and insert another string at a given position. It is commonly used for modifying text dynamically, such as replacing sections of a string or inserting new content within existing text. STUFF()
is primarily supported in SQL Server and follows a 1-based index system, meaning the first character starts at position 1. If the specified start position is invalid, or if the delete length exceeds the string length, the function may return NULL. It is often used in data cleansing, formatting outputs, and dynamically constructing strings.
Parameters:
original_string: The string to be modified
start_position: Position where to start deletion
length: Number of characters to delete
insert_string: String to insert at start_position
Example Use Cases:
-- Insert middle initial
-- Mask credit card numbers
-- Combine area code
Notes:
Behavior:Deletes specified characters and then inserts a new string; if the length is 0, it just inserts without deletion, and the position uses 1-based indexing.
Performance Considerations: Efficient for single-pass string modifications
Version Info: Primarily SQL Server function
Deprecated/Recommended Alternatives: CONCAT with SUBSTRING for other DBMS
Error Handling:
Error: Returns NULL if any parameter is NULL
Recommendation: Validate position and length inputs
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
INSERT()
INSERT(str,pos,len,newstr)
Returns NULL
PostgreSQL
OVERLAY()
OVERLAY(str PLACING new FROM pos FOR len)
Returns NULL
SQL Server
STUFF()
STUFF(str,pos,len,newstr)
Returns NULL
SQLite
REPLACE()
Custom Implementation
Returns NULL
BigQuery
REPLACE()
Custom Implementation
Returns NULL
Snowflake
REPLACE()
Custom Implementation
Returns NULL
Athena
REPLACE()
Custom Implementation
Returns NULL