Using SQL Length Function to Get String Length With Example

SQL LENGTH Function Summary: In this article, you will learn What is SQL Server LENGTH() function and How to use to Get String Length or the number of characters in a string.

Definition and Usage

The SQL LENGTH function returns the String Length or number of characters in a string. The LENGTH in SQL function is available in every relational database systems. Furthermore, few database systems use the SQL LEN function that has the same effect as the LENGTH function.

SQL LENGTH Function Syntax

The following syntax shows the LENGTH() function:

LENGTH(string)

In this syntax:

  • string: Required. If the input string is empty, the LENGTH Function returns the 0. if the input string is NULL then It returns NULL

    Therefore, the number of characters is the same as the number of bytes for the ASCII strings in SQL Server. For other character sets, its may be different.

.
Note:Important Note: In SQL Server LENGTH function returns the number of bytes in some relational database systems like as as MySQL and PostgreSQL. Furthermore, to get the number of characters in a string in MySQL and PostgreSQL, you use the SQL CHAR_LENGTH function instead.

SQL LENGTH Function Examples

A) Using SQL LENGTH() function with a literal string

The given below statement uses the LENGTH function to return the number of characters in the string.


SQL LENGTH function

B) Using SQL Server LENGTH() function with a column

The following given below Persons table to used for demonstration.

PersonID Name Address City
1 Noah Elijah Bridgetown Barbados
2 William Josiah Brussels Belgium
3 Elijah Connor Zagreb Croatia
4 Benjamin Hunter San Jose Costa Rica
5 Alexander Landon Roseau Dominica
6 Jacob Jonathan Paris France
7 Daniel Jeremiah Libreville Gabon
8 Owen Dominic Athens Greece
9 Gabriel Roman Tegucigalpa Honduras
10 Mateo Ezekiel Budapest Hungary

The following given below statement used the LENGTH() function to return the person name, city and its length, also sorts the name by the length of the person name.


LENGTH in SQL
Let see another example to understand the SQL LENGTH Function with a column.


tsql length

C) Using LENGTH Function with WHERE Condition

In this example, we used the persons table data and also used the LENGTH function inside the SQL Where Clause.

For instance, The following query will check whether the length of a Address, City is greater than 8 or not. If the given condition is TRUE, then the SELECT Statement will display the records.


example

Conclusion

In this tutorial, you have learned What is SQL Server LENGTH() function and How to use this function with different conditions to Get String Length or the number of characters in a string. I hope you will enjoy! if have any query, contact me, I have try to resolve the problem.