Strings

LENGTH

Counts how many characters a string has.

Syntax

LENGTH(<text>)
CHAR_LENGTH(<text>)

Returns the number of characters, spaces included. CHAR_LENGTH does the same and is part of the SQL standard. Often used to check length: a password that's too short, a name that's too long.

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.

The length of a string
SELECT LENGTH('PostgreSQL') AS letters,
LENGTH('SQL rocks') AS with_space;
letterswith_space
109
The length of each name
SELECT name, LENGTH(name) AS name_length
FROM employees;
namename_length
Emma4
Liam4
Olivia6
Noah4
Sophia6
Only names longer than 4 letters
SELECT name
FROM employees
WHERE LENGTH(name) > 4;
name
Olivia
Sophia

Watch out

It counts characters, not bytes: LENGTH('café') gives 4, even though it takes 5 bytes in memory. Bytes are counted by OCTET_LENGTH.

For NULL the result is NULL too, not 0. Only an empty string '' gives zero.

With the char(n) type, trailing spaces aren't counted: LENGTH('ab '::char(4)) gives 2, while for text it's 4.

Related functions

OCTET_LENGTHTRIMSUBSTRING

Learn more in the course