SELECT length(<column name>) FROM <table name>
Arguments and Return Value of the length Function
Number of characters = length(text)
text | Target column name or string literal |
Return value | The number of characters in the given text or null |
Type of return value | integer |
Examples of Using the length Function
Counting the Number of Characters in a String Literal
The following sample code displays the number of characters in the string literals ‘1234567890’ and ‘1234567890’. These are half-width and full-width characters respectively, but since the length function returns the number of characters, both results are 10.SELECT length('1234567890')
,length('1234567890');
Counting the Number of Characters in Text Stored in a Table
The following sample code displays the number of characters in the ‘soft_name’ column of the ‘sample_table’ table.SELECT *
,length(soft_name)
FROM sample_table;
Using as a Search Condition
You can use the length function as a search condition to search for records that match a specific number of characters. However, indexes do not work, so if there are many records, it may take time to process. If you frequently search using the number of characters, you will get the number of characters at the time of data insertion (insert) and store it, and create an index on that column.The following sample code extracts records where the number of characters in the ‘soft_name’ column of the ‘sample_table’ table is 10.
SELECT soft_name
FROM sample_table
WHERE length(soft_name) = 10;
Using for Sorting
If you use the length function in the ORDER BY clause, you can sort records in order of the number of characters. However, indexes do not work, so if there are many records, it may take time to process.The following sample code sorts the records in the ‘sample_table’ table in order of the number of characters in the ‘soft_name’ column and displays the results.
SELECT *
FROM sample_table
ORDER BY length(soft_name);
Notes on Using the length Function
The length function returns null, not 0, when null is given as an argument. If you want to return 0, use the COALESCE function to replace null with 0.Here is an example of using the COALESCE function to replace the result of the length function with 0 when it is null.
SELECT COALESCE(length(null), 0);
References
- PostgreSQL Official Documentation - 9.4. String Functions and Operators
- PostgreSQL Official Documentation - 9.5. Binary String Functions and Operators
- PostgreSQL Official Documentation - 9.18.2. COALESCE - 9.18. Conditional Expression
Test Environment
- PostgreSQL 16.1 on x86_64-pc-linux-musl, compiled by gcc (Alpine 12.2.1_git20220924-r10) 12.2.1 20220924, 64-bit
- pgAdmin 8.2
- Docker image: postgres:16.1-alpine3.18
- Docker image: dpage/pgadmin4
- Docker Desktop 4.26.1 (131620)
- Docker Engine Engine: 24.0.7
- Docker Compose v2.23.3-desktop.2
- Windows 10 Enterprise Version 22H2 OS Build 19045.3930 Experience: Windows Feature Experience Pack 1000.19053.1000.0