For working professionals
For fresh graduates
More
SQL Tutorial: Learn Structured…
1. SQL Tutorial
2. The Essential Guide To Understanding SQL In DBMS
3. SQL Commands
4. SQL Data Types
5. SQL Aliases
6. SQL INSERT INTO With Examples
7. Master SQL Update
8. SQL Delete Statement: A Complete Overview with Examples
9. SQL Delete Statement Example
10. SQL WHERE Clause
11. SQL AND Operator
12. SQL NOT Operator: A Comprehensive Guide
13. SQL Like
14. SQL Between Operator: A Complete Overview with Examples
15. Difference Between SQL and MySQL: Get to Know Your DBMS
16. MySQL Workbench
17. A Comprehensive Guide to MySQL Workbench Installation and Configuration
18. Mastering SQL: Your Comprehensive Guide to Becoming an SQL Developer
19. SQL CREATE TABLE With Examples
20. How To Add Columns In SQL: A Step-By-Step Guide
21. Drop Column in SQL: Everything You Need to Know
22. Index in SQL
23. Constraints in SQL: A Complete Guide with Examples
24. Schema in SQL
25. Entity Relationship Diagram (ERD) - A Complete Overview
26. Foreign Key in SQL with Examples
27. An Ultimate Guide to Understand all About Composite Keys in SQL
28. Normalization in SQL
29. Better Data Management: The Efficiency of TRUNCATE in SQL
30. Difference Between DELETE and TRUNCATE in SQL
31. SQL ORDER BY
32. SQL Not Equal Operator
33. SQL Intersect Operator: A Comprehensive Guide
34. SQL Union: Explained with Examples
35. SQL Case Statement Explained with Examples
36. Unleashing the CONCAT Function In SQL: String Manipulation Made Easy
37. Understanding and Mastering COALESCE in SQL
38. NVL in SQL
39. Understanding SQL Date Formats and Functions
40. DateDiff in SQL: A Complete Guide in 2024
41. SQL Wildcards
42. SQL DISTINCT: A Comprehensive Guide
43. LIMIT in SQL: A Comprehensive Tutorial
44. SQL Aggregate Functions
45. GROUP BY in SQL
46. SQL HAVING
47. EXISTS in SQL
48. SQL Joins
49. Inner Join in SQL
50. Left Outer Join in SQL
51. Full Outer Join in SQL
52. Cross Join in SQL
53. Self Join SQL
54. Left Join in SQL
55. Mastering SQL Substring
Now Reading
56. Understanding the ROW_NUMBER() Function in SQL
57. Cursor in SQL
58. Triggers In SQL
59. Stored Procedures in SQL
60. RANK Function in SQL
61. REPLACE in SQL
62. How to Delete Duplicate Rows in SQL
63. Transact-SQL
64. INSTR in SQL
65. PostgreSQL vs MySQL: Explore Key Differences
66. Mastering SQL Server Management Studio (SSMS): A Comprehensive Guide
67. Auto-Increment in SQL
68. Unveiling the Power of SQL with Python
69. SQL Vs NoSQL: Key Differences Explained
70. Advanced SQL
71. SQL Subquery
72. Second Highest Salary in SQL
73. Database Integrity Constraints: Everything You Need to Know
74. Primary Key In SQL: A Complete Guide in 2024
75. A Comprehensive Guide on View in SQL
76. Understanding PostgreSQL: A Complete Tutorial
77. SQL Injection Attack
78. MySQL database
79. What is SQLite
80. SQLite
81. ALTER Command in SQL
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.
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.
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:
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:
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:
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:
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.
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:
Expected Output:
order_number | extracted_substring |
ORD1234 | 1234 |
ORD5678 | 5678 |
ORD91011 | 1011 |
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:
Expected Output:
product_name | extracted_substring |
Laptop | top |
Smartphone | artph |
Headphones | adpho |
Tablet | ablet |
Smartwatch | rtwat |
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.
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:
Expected Output:
full_name |
John Doe |
Alice Smith |
Michael Brown |
Sarah Johnson |
The substring in SQL can be used with some other functions too. Here, I detail the use of some possible combinations with examples.
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:
Expected Output:
generated_username |
JohDoe |
AliSith |
MicBrown |
SarJohn |
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:
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.
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.
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.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.