PostgreSQL left() Function
The PostgreSQL left()
function extracts the leftmost specified number of characters in the gaven string and returns them as a string.
If you want to extract a certain number of characters from the right of a string, use the right()
function.
left()
Syntax
This is the syntax of the PostgreSQL left()
function:
left(str, num)
Parameters
str
-
Required. The string where to extract characters.
num
-
Required. The number of characters to extract. It can be positive or negative. If it is negative, the
left()
function returns all characters except for the rightmost-num
characters.
Return value
The PostgreSQL left()
function returns the leftmost num
characters of the string str
.
If num
is negative, the left()
function returns all characters in the string except for the rightmost -num
characters.
The left()
function will return str
if num
is greater than the length of str
.
If num
equals 0
, the left()
function will return empty ''
.
If the parameter is NULL
, the function will return NULL
.
left()
Examples
This example shows how to use the left()
function to get the leftmost 2 characters of the string hello
.
SELECT left('hello', 2) AS "left('hello', 2)";
left('hello', 2)
------------------
he
You can provide a negative number for num
:
SELECT left('hello', -3) AS "left('hello', -3)";
left('hello', -3)
-------------------
he
Here, since num
is -3
, the characters other than the rightmost 3 characters are returned. That is: he
.