SQL Standard

SQL String Length Function

In this short article, we will learn how to determine the length of a string in SQL. Before diving into the actual content, remember that we reference the ANSI Standard SQL definitions when we say SQL. Although we cover the SQL language extensions of various database engines, it’s good to note the difference.

Standard SQL Length Function

The Standard SQL function to determine the length of a string is LENGTH(). This function takes a string or bytes and returns the string.

The syntax is as shown below.:

LENGTH(value);

Consider an example shown below:

SELECT length('hi') as length;

The query above should return the length of the provided string. An example output is as shown below:

length
--------
2

NOTE: Keep in mind that the length here indicates the number of Unicode characters in the provided string.

You can check Unicode characters as shown below:

https://unicode.org/standard/standard.html

Extended String Length Function

Various database engines implemented and extended versions of the SQL Standard. One example is the string length function.

In database engines such as MySQL, this function is renamed to LEN. However, the usage is similar to the one shown above.

The syntax is as shown below:

LEN(value);

The function takes the string as the argument and returns the number of characters in the string.

An example usage is as shown below:

SELECT LEN('hi');

This should return:

length
--------
2

You can also use the LENGTH (SQL Standard), and LEN(extended) functions to determine the length of strings in a column.

An example usage is as shown:

SELECT first_name, LENGTH(first_name) FROM customer;

In the example above, we use a sample customer’s table to get the length of the first_name column.

The resulting set is as shown:

first_name | length
------------+--------
MARY | 4
PATRICIA | 8
LINDA | 5
BARBARA | 7
ELIZABETH | 9

Closing

In this article, we discuss how to determine the length of a string using the LENGTH function in Standard SQL and LEN in extended SQL version.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list