1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

81 Lessons
55

Mastering SQL Substring: Practical Examples for Efficient Data Extraction

Updated on 19/07/2024438 Views

Introduction

SQL substring functions are crucial in extracting specific portions of text or characters from strings stored in a database. Whether isolating a part of an email address or extracting a portion of a product description, mastering substring operations is essential for effective data manipulation. Let’s explore SQL substring functions, their syntax, and practical applications, and provide clear examples that demonstrate how to use them. 

Overview

SQL substring functions are powerful tools for extracting specific segments of text or characters from strings within a database. Here, we will provide an in-depth exploration of SQL substring functions, accompanied by practical examples to illustrate their usage. Starting with an overview of the syntax and parameters involved, we'll proceed to demonstrate various scenarios where substring operations can be applied effectively. From extracting substrings at the beginning, middle, or end of a string to utilizing aliases and combining substring functions with other SQL operations, this guide will cover a wide range of examples to help you master substring manipulation in SQL.

What is SQL Substring?

SQL substring is a function in SQL that is used to extract a portion of a string based on a specified starting position and length. It allows you to isolate specific characters or segments from a larger string, facilitating data manipulation and analysis. Let's delve deeper with SQL substring examples:


1. Extracting Substrings From the Beginning:

Let’s assume, we have a table named "employees" with a column named "full_name" containing the names of employees. We want to extract the first name from each full name.

SQL Query:

Code- 

SELECT SUBSTRING(full_name, 1, CHARINDEX(' ', full_name) - 1) AS first_name

FROM employees;

Explanation:

  • SUBSTRING: The SQL Substring function.
  • full_name: The column from which we want to extract the substring.
  • 1: The starting position from which the extraction begins.
  • CHARINDEX(' ', full_name) - 1: The length of the substring to be extracted, determined by finding the position of the first space in the full name and subtracting 1.
  • AS first_name: This renames the extracted substring column for clarity.

Expected Output:

full_name

extracted_substring

John Doe

John

Alice Smith

Alice

Michael Brown

Michael

Sarah Johnson

Sarah

SUBSTRING() function in SQL 

The SUBSTRING() function in SQL is used to extract a substring from a string. It requires specifying the string expression, the starting position of the substring, and optionally, the length of the substring to be extracted. Here's an example:Suppose we have a table named "products" with a column called "product_name" containing the names of various products. We want to extract a substring from each product name to isolate specific keywords.SQL Query:

Code- 

SELECT product_name,

       SUBSTRING(product_name, 1, 5) AS extracted_substring

FROM products;

Explanation:

  • SUBSTRING: The SQL substring function.
  • product_name: The column from which we want to extract the substring.
  • 1: The starting position from which the extraction begins (beginning of the string).
  • 5: The length of the substring to be extracted (5 characters).
  • AS extracted_substring: This renames the extracted substring column for clarity.

Expected Output:

product_name

extracted_substring

Laptop

Lapto

Smartphone

Smart

Headphones

Headp

Tablet

Table

Smartwatch

Smart

The SUBSTRING() function is a versatile tool in SQL for extracting specific portions of text data from strings, facilitating various data manipulation tasks.

LEFT() function in SQL

The LEFT() function in SQL is used to extract a specified number of characters from the left side of a string. It is similar to the SUBSTRING() function but provides a more intuitive way to extract substrings from the beginning of a string. Here's an example:Suppose we have a table named "products" with a column called "product_name" containing the names of various products. We want to extract the first 5 characters from each product name.

SQL Query:

Code- 

SELECT product_name,

       LEFT(product_name, 5) AS extracted_substring

FROM products;

Explanation:

  • LEFT: The SQL LEFT() function.
  • product_name: The column from which we want to extract the substring.
  • 5: The number of characters to be extracted from the left side of the string.
  • AS extracted_substring: This renames the extracted substring column for clarity.

Expected Output:

product_name

extracted_substring

Laptop

Lapto

Smartphone

Smart

Headphones

Headp

Tablet

Table

Smartwatch

Smart

The LEFT() function provides a convenient way to extract substrings from the beginning of a string, making it useful for various data manipulation tasks in SQL.

2. Extracting Substrings From the End or RIGHT() Function in SQL

To extract substrings from the end of a string in SQL, we can use a combination of functions such as LEN() and RIGHT(). Here's how it works with an example:Suppose we have a table named "orders" with a column called "order_number" containing unique identifiers for each order. We want to extract the last 4 characters from each order number.

SQL Query:

Code- 

SELECT order_number,

       RIGHT(order_number, 4) AS extracted_substring

FROM orders;

Explanation:

  • RIGHT: The SQL RIGHT() function.
  • order_number: The column from which we want to extract the substring.
  • 4: The number of characters to be extracted from the end of the string.
  • AS extracted_substring: This renames the extracted substring column for clarity.

Expected Output:

order_number

extracted_substring

ORD1234

1234

ORD5678

5678

ORD91011

1011

3. Extracting Substrings from the Middle

To extract substrings from the middle of a string in SQL, we can use a combination of functions such as SUBSTRING() and LEN(). Here's how it works with an example:Suppose we have a table named "products" with a column called "product_name" containing the names of various products. We want to extract a substring from the middle of each product name.

SQL Query:

Code- 

SELECT product_name,

       SUBSTRING(product_name, LEN(product_name)/2, 5) AS extracted_substring

FROM products;

Explanation:

  • SUBSTRING: The SQL SUBSTRING() function.
  • product_name: The column from which we want to extract the substring.
  • LEN(product_name)/2: The starting position from which the extraction begins, calculated as half of the length of the string.
  • 5: The length of the substring to be extracted.
  • AS extracted_substring: This renames the extracted substring column for clarity.

Expected Output:

product_name

extracted_substring

Laptop

top

Smartphone

artph

Headphones

adpho

Tablet

ablet

Smartwatch

rtwat

SUBSTRING in SQL Server

In SQL Server, the SUBSTRING function is used to extract a substring from a string. Its syntax is:

Code- 

SUBSTRING(string_expression, start, length)

- string_expression: The string from which the substring will be extracted.- start: The position within the string where the extraction will begin (1-based index).- length: Optional. The length of the substring to be extracted. If omitted, the substring starting from the start position until the end of the string will be returned.

Example:

Code-

SELECT SUBSTRING('Hello, World!', 1, 5) AS SubstringResult;

This will return: "Hello"It extracts the substring starting from the first character and with a length of 5 characters.

Using Aliases in SQL

Aliases are temporary names assigned to columns or tables in SQL queries to make the output more readable or to simplify complex expressions. Here's how to use aliases with an example:Suppose we have a table named "employees" with columns "first_name" and "last_name." We want to concatenate these columns and display the result with a meaningful alias.

SQL Query:

Code- 

SELECT CONCAT(first_name, ' ', last_name) AS full_name

FROM employees;

Explanation:

  • CONCAT: The SQL CONCAT() function is used to concatenate the "first_name" and "last_name" columns.
  • AS full_name: This assigns the concatenated result a temporary name "full_name" using an alias.

Expected Output:

full_name

John Doe

Alice Smith

Michael Brown

Sarah Johnson

Using Substring with Other Functions

The substring in SQL can be used with some other functions too. Here, I detail the use of some possible combinations with examples.

1. Examples With CONCAT()

The CONCAT() function in SQL is often used in combination with SUBSTRING() to concatenate substrings extracted from different parts of a string. Here's an example:Let’s assume, we have a table named "employees" with columns "first_name" and "last_name." We want to concatenate the first three characters of the first name with the last three characters of the last name.

SQL Query:

Code-

SELECT CONCAT(SUBSTRING(first_name, 1, 3), SUBSTRING(last_name, LEN(last_name) - 2, LEN(last_name))) AS generated_username

FROM employees;

Explanation:

  • CONCAT: The SQL CONCAT() function concatenates the substrings extracted from the "first_name" and "last_name" columns.
  • SUBSTRING: The SQL SUBSTRING() function extracts the first three characters from the "first_name" column and the last three characters from the "last_name" column.
  • LEN: The SQL LEN() function is used to get the length of the "last_name" column to calculate the starting position for extracting the last three characters.
  • The result is assigned a temporary name "generated_username" using an alias.

Expected Output:

generated_username

JohDoe

AliSith

MicBrown

SarJohn

2. Examples With WHERE Clause

Using SUBSTRING() with the WHERE clause allows filtering rows based on specific conditions applied to substrings. Here's an example:Suppose we have a table named "products" with a column called "product_code" containing unique identifiers for each product. We want to retrieve products whose codes start with "ABC."

SQL Query:

Code- 

SELECT *

FROM products

WHERE SUBSTRING(product_code, 1, 3) = 'ABC';

Explanation:

  • SUBSTRING: The SQL SUBSTRING() function extracts the first three characters from the "product_code" column.
  • The WHERE clause filters rows where the extracted substring equals 'ABC.'

Expected Output:

product_code

ABC123

ABC456

Using SUBSTRING() with other SQL functions or clauses allows for versatile data manipulation and filtering based on specific substring conditions.

Conclusion

Wrapping up, SQL substring functions are invaluable tools for extracting specific segments of text or characters from strings within a database. Through the examples provided, we've explored various scenarios demonstrating the versatility of SQL substring operations, from extracting substrings at the beginning, middle, and end of strings to utilizing them with other functions and clauses like CONCAT() and WHERE.Finally, mastering SQL substring functions not only enhances your ability to manipulate data efficiently but also enables you to perform complex queries and analyses with ease. Whether you're generating usernames, filtering data, or creating custom reports, a solid understanding of SQL substring operations empowers you to unlock the full potential of your database management skills.

FAQs

Q. How to find the last char in SQL?

Ans. You can find the last character in a string using the RIGHT() function combined with the LEN() function to determine the length of the string. Here's an example:

Code- 

SELECT RIGHT(column_name, 1) AS last_char

FROM table_name;

This query retrieves the last character from the "column_name" in the "table_name."

Q. How to use multiple SUBSTRING in SQL?

Ans. In SQL, you can use multiple SUBSTRING functions to extract different substrings from a string. Here's an example:

Code- 

SELECT SUBSTRING(column_name, 1, 3) AS substring1,

       SUBSTRING(column_name, 4, 5) AS substring2

FROM table_name;

This query extracts two substrings from the "column_name" in the "table_name." The first SUBSTRING extracts characters starting from position 1 and spanning 3 characters, while the second SUBSTRING starts from position 4 and spans 5 characters.

Q. Can we use Substr in insert statements?

Ans. You cannot use the SUBSTR function directly within an INSERT statement in SQL. The SUBSTR function is typically used to extract a substring from an existing string. In an INSERT statement, you're adding new data to a table rather than manipulating existing data. However, you can use the SUBSTR function to extract values from existing columns and then insert those values into another table using an INSERT INTO...SELECT statement.

Q. How many times a substring appears in a string?

Ans. To find how many times a substring appears in a string, you can use the CHARINDEX function in SQL, which returns the starting position of the substring within the string. Then, you can use this information to count occurrences.

Ankit Mittal

Ankit Mittal

Working as an Senior Software Engineer at upGrad, with proven experience across various industries.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...