Function Reference

SUBSTRING

Returns part of a string: length characters starting at position start.

PostgreSQL 17.5
SUBSTRING(string [FROM start] [FOR length])

Parameters

stringtext
Source string
startintegeroptional
Position of the first character, starting from 1, 1 by default
lengthintegeroptional
Number of characters, to the end of the string by default

Return value

A substring (text); an empty string if start is greater than the string length

Examples

First four characters

PostgreSQL 17.5
SELECT SUBSTRING(
		'PostgreSQL'
		FROM 1 FOR 4
	);
substring
Post

From the fifth character to the end

PostgreSQL 17.5
SELECT SUBSTRING(
		'PostgreSQL'
		FROM 5
	);
substring
greSQL

Comma syntax

PostgreSQL 17.5
SELECT SUBSTRING('PostgreSQL', 8, 3);
substring
SQL

Details

The arguments can also be passed separated by commas: SUBSTRING(string, start, length).

If start is less than 1, the positions before the string also count towards length.

A negative length causes an error instead of returning an empty string as in MySQL. The short form of the function is SUBSTR.

See also

Where to learn