What is the usage of the substring function in SQL?

The SUBSTRING() function in SQL is used to extract a portion of a string.

The basic syntax is as follows:

SUBSTRING(string, start_position, length)
  1. String: The string to be extracted.
  2. start position: the beginning position extracted. The counting of the starting position begins from 1.
  3. Length: An optional parameter that specifies the length of the substring to be extracted. If this parameter is omitted, it represents extracting all characters from the starting position to the end of the string.

For example, consider a table named customers, with a column named name storing the names of the customers. To extract the first 3 characters from the name column, you can use the following SQL query:

SELECT SUBSTRING(name, 1, 3) 
FROM customers;

This will return the first 3 characters of each customer’s name.

Additionally, the SUBSTRING() function can be used together with other string functions, such as conditions in the WHERE clause or sorting in the ORDER BY clause, to manipulate and operate on strings as needed.

bannerAds