How to Remove Prefix From Field in SQL Server?


To remove a prefix from a field in SQL Server, you can use the SUBSTRING function along with the LEN function to determine the length of the prefix. Here are two methods to achieve this:

Method 1: Using SUBSTRING and LEN functions

Suppose you have a table named employees with a column named emp_name that contains names with a prefix "Mr." or "Ms.". To remove the prefix from the names, you can use the following SQL query:

UPDATE employees
SET emp_name = SUBSTRING(emp_name, LEN('Mr. ') + 1, LEN(emp_name))
WHERE emp_name LIKE 'Mr. %'

UPDATE employees
SET emp_name = SUBSTRING(emp_name, LEN('Ms. ') + 1, LEN(emp_name))
WHERE emp_name LIKE 'Ms. %'

In this query, we are using the SUBSTRING function to extract the substring from the original string starting from the length of the prefix plus one (to exclude the prefix) and ending at the end of the string. The LEN function is used to determine the length of the prefix.

Method 2: Using REPLACE function

Another way to remove the prefix from a field is to use the REPLACE function. Here's an example:

UPDATE employees
SET emp_name = REPLACE(emp_name, 'Mr. ', '')
WHERE emp_name LIKE 'Mr. %'

UPDATE employees
SET emp_name = REPLACE(emp_name, 'Ms. ', '')
WHERE emp_name LIKE 'Ms. %'

In this query, we are using the REPLACE function to replace the prefix with an empty string. The LIKE operator is used to filter the rows that start with the prefix.

Both methods will achieve the same result, but the first method may be more efficient for large datasets as it avoids replacing the prefix with an empty string.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.