w3resource

PostgreSQL LENGTH() function

LENGTH() function

The PostgreSQL length() function is used to determine the number of characters in a given string. It is useful for evaluating string lengths in various contexts, such as data validation, formatting, and analysis.

Uses of LENGTH() Function
  • Determine String Length: Calculate the number of characters in a string.

  • Data Validation: Ensure that strings meet certain length requirements.

  • Filtering Data: Use in WHERE clauses to filter results based on string length.

  • Data Formatting: Format output based on string length for better readability.

  • Performance Optimization: Optimize queries and data storage by analyzing string lengths.

  • Combining with Other Functions: Use alongside other string functions for complex data manipulations.

Syntax:

length(<string>)

PostgreSQL Version: 9.3

Pictorial Presentation of PostgreSQL LENGTH() function

Pictorial presentation of PostgreSQL LENGTH() function

Example: PostgreSQL LENGTH() function:

In the example below the length function returns the length of the given string 'w3resource'.

Code:

SELECT length('w3resource')
AS "Length of a String";

Sample Output:

 Length of a String
--------------------
                 10
(1 row)

Example of PostgreSQL LENGTH() function using column :

Sample Table: employees


The example below, returns the first_name and the length of first_name ( how many characters contain in the first name ) from the employees where the length of first_name is more than 7.

Code:

SELECT first_name,length(first_name) 
AS "Length of a First Name" 
FROM employees 
WHERE length(first_name)>7;

Sample Output:

 first_name  | Length of a First Name
-------------+------------------------
 Alexander   |                      9
 Jose Manuel |                     11
 Alexander   |                      9
 Christopher |                     11
 Danielle    |                      8
 Harrison    |                      8
 Elizabeth   |                      9
 Jonathon    |                      8
 Kimberely   |                      9
 Jennifer    |                      8
 Jennifer    |                      8
(11 rows)

Previous: LEFT function
Next: LPAD function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/length-function.php