SQL Server SUBSTRING() Function

The SUBSTRING() function in SQL Server extracts a portion of a string, starting at a specified position and extending for a given length. It's a fundamental string manipulation function.



SUBSTRING(): Definition and Usage

This function is invaluable for pulling out specific parts of text data. You might use it to extract usernames from email addresses, extract postal codes from addresses, or isolate keywords from longer text strings. Remember that the starting position is 1 (not 0, as in some programming languages).

Syntax

Syntax

SUBSTRING(string, start, length)
      

Parameter Values

Parameter Description
string The string from which to extract the substring. This is required.
start The starting position of the substring (the first character is position 1). This is required.
length The number of characters to extract. Must be a positive integer. This is required.

Examples

Extracting a Substring from a Literal String

This extracts the first three characters ('SQL') from the string 'SQL Tutorial'.

Syntax

SELECT SUBSTRING('SQL Tutorial', 1, 3) AS ExtractString;
      
Output

SQL
      

Extracting a Substring from a Column

This extracts the first five characters from the 'CustomerName' column in the 'Customers' table (assuming such a table and column exist).

Syntax

SELECT SUBSTRING(CustomerName, 1, 5) AS ExtractString
FROM Customers;
      
Output

ExtractString
--------------
(First five characters of each CustomerName from the Customers table)
      

Extracting a Long Substring

Even if you ask for more characters than exist, it will only return the available characters.

Syntax

SELECT SUBSTRING('SQL Tutorial', 1, 100) AS ExtractString;
      
Output

SQL Tutorial