PostgreSQL LENGTH() Function
Summary: in this tutorial, you will learn how to use the PostgreSQLLENGTH()
functions to get the number of characters of a string.
Introduction to the PostgreSQL LENGTH() function
The PostgreSQLLENGTH()
function returns the number of characters in a string.
Here’s the basic syntax for theLENGTH()
function:
LENGTH(string);
TheLENGTH()
function accepts a string as a parameter. It can be any of the followingdata types:
- character or char
- character varying or varchar
- text
TheLENGTH()
function returns an integer that represents the number of characters in the string. It returns NULL if the string is null.
PostgreSQL provides theCHAR_LENGTH()
andCHARACTER_LENGTH()
functions that provide the same functionality as theLENGTH()
function.
PostgreSQL LENGTH() function examples
Let’s explore some examples of using theLENGTH()
function.
1) Basic PostgreSQL LENGTH() function examples
The following example uses theLENGTH()
function to get the length of a string:
SELECT LENGTH ('PostgreSQL Tutorial');
Output:
length-------- 19(1 row)
If you pass NULL to theLENGTH()
function, it returns NULL.
SELECT LENGTH (NULL);
Output:
length-------- null(1 row)
2) Using the PostgreSQL LENGTH() function with table data example
We’ll use thecustomer
table from thesample database:
The following example uses the
LENGTH()
function to retrieve the first names and the number of characters of first names from thecustomer
table:
SELECT first_name, LENGTH (first_name) lenFROM customerORDER BY len;
Output:
first_name | len-------------+----- Jo | 2 Sam | 3 Roy | 3 Eva | 3 Don | 3 Dan | 3...
Summary
- Use the PostgreSQL
LENGTH()
function to get the number of characters of a string.
Last updated on