PostgreSQL LENGTH Function

PostgreSQL LENGTH Function

PostgreSQL LENGTH Function

The LENGTH function in PostgreSQL is used to determine the number of characters or bytes in a string. It is commonly used for validations, data analysis, and formatting.

1. Basic Syntax

SELECT LENGTH(string);
  • Returns the number of characters in the given string.
  • Works with VARCHAR, TEXT, CHAR, and other string types.

Example: Basic Usage

SELECT LENGTH('Hello, World!');

Output: 13 (counts spaces and punctuation)

2. Using LENGTH on Table Columns

You can use LENGTH to check the length of column values.

Example: Find Length of Names

SELECT first_name, LENGTH(first_name) AS name_length FROM employees;

Output:

first_namename_length
John4
Alexander9

3. LENGTH vs. OCTET_LENGTH (Bytes vs. Characters)

FunctionMeasuresExample
LENGTH()Character count'Hello' → 5
OCTET_LENGTH()Byte size'Hello' → 5 (ASCII)

Example: Compare LENGTH and OCTET_LENGTH

SELECT LENGTH('Ñandú') AS char_count, OCTET_LENGTH('Ñandú') AS byte_size;

Output (UTF-8 Encoding):

char_countbyte_size
56

🔹 Explanation:

  • 'Ñandú' has 5 characters but 6 bytes due to the special character Ñ.

4. Find Records Where Length is Greater Than X

SELECT * FROM employees WHERE LENGTH(last_name) > 8;

Finds employees with last names longer than 8 characters.

5. Using LENGTH with TRIM (Ignore Spaces)

SELECT LENGTH(TRIM(' PostgreSQL '));

Output: 10 (removes leading & trailing spaces before measuring length)

6. Example: Validate Input Length

SELECT first_name, LENGTH(first_name) AS name_length FROM employees WHERE LENGTH(first_name) < 3;

Finds names with fewer than 3 characters (e.g., "Al", "Jo").

7. Summary

Use CaseQueryOutput Example
Basic String LengthSELECT LENGTH('Hello');5
Column LengthSELECT LENGTH(first_name) FROM employees;Varies
Filter by LengthWHERE LENGTH(last_name) > 8Names > 8 chars
Byte Size of StringSELECT OCTET_LENGTH('Ñandú');6
Ignore SpacesSELECT LENGTH(TRIM(' ABC '));3
Would you like a real-world example for data validation? 🚀
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close