SQL Server: basic functions (part 9) - Substring
One of the most interesting Sql function, when working with strings, is Substring. Basically, it returns a part of a string, given the starting point and the length (number of characters).
The syntax
Let's see Substring syntax:
That's all for now. See you next time!
The syntax
Let's see Substring syntax:
SUBSTRING ( expression , start , length )
In the function we have to declare:- expression, which is the string we want to manipulate;
- start, which is an integer or bigint indicating where to start the extraction. If it is 0 (zero), the starting point will be at the beginning of the expression -1 (see below in "examples"). If start is greater than the length of expression, the function will return a zero-length expression;
- length, which is a positive integer or bigint indicating how many characters to consider from the start (starting point).
Examples
Just as a simple example,SUBSTRING('Hello!', 3, 4)
will returnllo!
Another example would be:SUBSTRING('Hello!', 1, 2)
that returnsHe
Strangely enough, there are some odd behaviours with the function when start is either zero or a negative number.SUBSTRING('Hello!', 0, 3)
will returnHe
AndSUBSTRING('Hello!', -1, 3)
will returnH
That's all for now. See you next time!