How to Use LENGTH Function to Find String Length in SQL?

Learn via video course
FREE
View all courses
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
Topics Covered

The LENGTH function in SQL returns the length of the word or the number of characters present in the string. The LENGTH function is a type of string function. We can find the LENGTH function in every relational database like SQL Server, MySQL, PostgreSQL, etc. We use LEN instead of LENGTH in a few databases, as in SQL Server.

Syntax of LENGTH Function

The following illustrates the syntax of the LENGTH function.

Parameters of LENGTH in SQL

The LENGTH function only accepts one parameter, i.e. string whose length is to be determined. It takes strings in the following formats:

  • Raw string
  • A string variable
  • An expression returning string
  • Float or Numeric values

Return Value of LENGTH in SQL

The LENGTH function returns the length of the string in bytes. If the input string is empty, the LENGTH returns 0. It returns NULL if the input string is NULL.

Learn More about Advanced Concepts of SQL

Examples of LENGTH Function in SQL

Example 1

In this example, we will find the string "Scaler" length.

Output:

In this example, we have found the length of the word "Scaler". The output is 6.

Example 2

In this example, we will take the length of the floating value from the demo table.

Table Demo

Taxnonametaxrate
1Ryan6.55
2Joanna8.243
3Jennie5.2455
4Max7.43
5Siya6.5

Output:

Taxnonametaxratelen_taxrate
1Ryan6.554
2Joanna8.225
3Jennie5.24556
4Max7.434
5Siya6.53

In the above example, the LENGTH function returns the length of the float value.

Example 3

In this example, we will find the length of the item_name from the below table:

Table Items

item_noitem_namePrice
1Biscuit50
2Choclates100
3Pasta120
4Mayonnaise90
5Ketchup80

Output:

item_noitem_namePricelen_of_item
1Biscuit507
2Choclates1009
3Pasta1205
4Mayonnaise9010
5Ketchup807

In this way, we can use a LENGTH function to calculate the length of any given string.

Conclusion

  • The length function calculates the length of a string.
  • It returns the length of the given string in bytes.
  • The LENGTH function returns a NULL value if the input string is NULL.
  • The LENGTH function is used in SELECT statements and data manipulation statements.