StringsSQL standard

SUBSTRING

Cuts out part of a string: from the position you need and of the length you need.

Syntax

SUBSTRING(<text> FROM <start>)
SUBSTRING(<text> FROM <start> FOR <length>)
SUBSTRING(<text>, <start>, <length>)

Positions are counted from 1. FROM — which character to start at, FOR — how many characters to take; without FOR, everything up to the end is taken. The comma form does the same.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Parts of a word
SELECT SUBSTRING('database' FROM 1 FOR 4) AS first_part,
SUBSTRING('database' FROM 5) AS rest;
first_partrest
database
The first letter of a name
SELECT name,
SUBSTRING(name FROM 1 FOR 1) AS initial
FROM employees;
nameinitial
EmmaE
LiamL
OliviaO
NoahN
SophiaS
The country code from a phone number
SELECT name, phone,
SUBSTRING(phone FROM 1 FOR 3) AS country_code
FROM employees;
namephonecountry_code
Emma+44 7700 900123+44
LiamNULLNULL
Olivia+44 7700 900456+44
Noah+44 7700 900789+44
SophiaNULLNULL

Where there's no phone number, the result is NULL too.

Watch out

Positions start at 1, not 0. SUBSTRING('abc' FROM 0 FOR 2) returns just a: there's no “zeroth” character, but it still takes up a place in the length.

FOR is a length, not an end position: SUBSTRING('database' FROM 5 FOR 3) gives bas.

If you pass a pattern instead of a number, SUBSTRING searches with a regular expression: SUBSTRING('order #1234' FROM '[0-9]+') gives 1234.

Learn more in the course