Microsoft SQL Server

Chapter 7 - DQL (Data Query Language)

STRING functions

In Microsoft SQL Server, string functions are used to manipulate and handle string data. These functions allow you to perform operations such as extracting parts of a string, concatenating strings, replacing values, and formatting text. For beginners, mastering string functions is essential for working with textual data stored in your database, whether you’re cleaning data, formatting output, or analyzing text.

Below is a detailed explanation of some of the most commonly used string functions in SQL Server, with examples and best practices.

1. LEN() – Length of a String

The LEN() function returns the number of characters in a string, excluding trailing spaces.

SELECT LEN(column_name) AS Length FROM table_name;

Example:

SELECT ProductName, LEN(ProductName) AS NameLength FROM Products;

This query returns the length of each product name in the Products table.

2. LEFT() – Extracting the Left Part of a String

The LEFT() function returns the leftmost characters from a string, based on the number of characters specified.

SELECT LEFT(column_name, number_of_characters) AS LeftPart FROM table_name;

Example:

SELECT ProductName, LEFT(ProductName, 5) AS ShortName FROM Products;

This query extracts the first 5 characters from each product name.

3. RIGHT() – Extracting the Right Part of a String

The RIGHT() function returns the rightmost characters from a string, based on the number of characters specified.

SELECT RIGHT(column_name, number_of_characters) AS RightPart FROM table_name;

Example:

SELECT ProductName, RIGHT(ProductName, 3) AS EndChars FROM Products;

This query extracts the last 3 characters from each product name.

4. SUBSTRING() – Extracting a Substring

The SUBSTRING() function extracts a substring from a string, starting at a specified position and extracting a specified number of characters.

SELECT SUBSTRING(column_name, start_position, length) AS Substring FROM table_name;

Example:

SELECT ProductName, SUBSTRING(ProductName, 2, 5) AS MidChars FROM Products;

This query extracts 5 characters starting from the second character in each product name.

5. REPLACE() – Replacing Substring

The REPLACE() function replaces all occurrences of a specified substring within a string with another substring.

SELECT REPLACE(column_name, 'old_value', 'new_value') AS ReplacedString FROM table_name;

Example:

SELECT ProductName, REPLACE(ProductName, 'Phone', 'Mobile') AS NewProductName FROM Products;

This query replaces the word "Phone" with "Mobile" in the ProductName column.

6. UPPER() and LOWER() – Changing Case

The UPPER() function converts a string to uppercase, while the LOWER() function converts a string to lowercase.

SELECT UPPER(column_name) AS Uppercase, LOWER(column_name) AS Lowercase FROM table_name;

Example:

SELECT ProductName, UPPER(ProductName) AS UppercaseName, LOWER(ProductName) AS LowercaseName FROM Products;

This query returns both the uppercase and lowercase versions of each product name.

7. CONCAT() – Concatenating Strings

The CONCAT() function is used to combine two or more strings into one.

SELECT CONCAT(column1, column2) AS ConcatenatedString FROM table_name;

Example:

SELECT CONCAT(ProductName, ' - ', Category) AS ProductCategory FROM Products;

This query concatenates the product name and category with a hyphen between them.

8. TRIM() – Removing Leading and Trailing Spaces

The TRIM() function removes any leading or trailing spaces from a string.

SELECT TRIM(column_name) AS TrimmedString FROM table_name;

Example:

SELECT TRIM(ProductName) AS CleanedProductName FROM Products;

This query removes any leading or trailing spaces from the product names.

9. Best Practices for Using String Functions

  1. Use LEN() to Validate Data Length – Use the LEN() function to check the length of strings, which is especially useful for validating data such as phone numbers or codes.

    SELECT CustomerName, LEN(CustomerName) AS NameLength FROM Customers;
  2. Extract Parts of Strings with LEFT(), RIGHT(), and SUBSTRING() – When you need specific parts of a string, use LEFT(), RIGHT(), or SUBSTRING() to extract meaningful portions, such as prefixes, suffixes, or specific characters.

    SELECT LEFT(ProductID, 3) AS ProductPrefix FROM Products;
  3. Use REPLACE() for Data Cleaning – Use the REPLACE() function to clean data by removing or replacing unwanted characters or substrings.

    SELECT REPLACE(Email, 'old.com', 'new.com') AS UpdatedEmail FROM Customers;
  4. Combine Strings with CONCAT() – Use CONCAT() when you need to combine multiple columns or strings, such as creating full names from first and last names.

    SELECT CONCAT(FirstName, ' ', LastName) AS FullName FROM Employees;
  5. Handle Case Sensitivity with UPPER() and LOWER() – Use UPPER() or LOWER() to ensure consistent data formatting when filtering, especially for case-sensitive databases.

    SELECT * FROM Products WHERE LOWER(ProductName) = 'laptop';
  6. Remove Unwanted Spaces with TRIM() – Always use TRIM() to clean up data, particularly when dealing with user input that might have extra spaces.

    SELECT TRIM(CustomerName) AS CleanedCustomerName FROM Customers;

By mastering string functions in SQL Server, you can easily manipulate and format textual data, making it easier to retrieve, display, and clean data stored in your database tables. These functions are essential for data processing and reporting in SQL.

Tansy SQL Course | STRING functions | Chapter 7 | Lesson 35 - Video Thumbnail
Comments(0 comments)

Comments Not Found