SQL Length of String

Strings are a fundamental part of any database administrator or programmer. They allow you to store textual information within a database.

This article will discuss how you can determine the length of a string type in Standard SQL.

In Standard SQL, there are three main methods to determine the length of a string.

SQL Byte Length Function

The first method you can use to determine the length of a string is the byte_length function. This function takes the string as the input parameter and returns the length of the string in bytes.

The function syntax is shown below:

BYTE_LENGTH(VALUE)

Keep in mind that the function’s return type is a 64-bit integer.

An example usage is shown below:

SELECT
  BYTE_LENGTH('Hello') AS lenght_in_bytes;

The example statement takes the string “Hello” and returns its length in bytes. An example output is as shown:

lenght_in_bytes
5

SQL Char_Length Function

The second method you can use to determine the length of a string is the char_length function. Similarly, the function takes a string and returns the length of the string in characters.

The function syntax is shown below:

CHAR_LENGTH(VALUE)

An example usage is shown below:

SELECT
  CHAR_LENGTH('Hello') AS lenght_in_characters;

This should return the output as shown:

lenght_in_characters
5

Note that in some cases, you may find this function renamed to  CHARACTER_LENGTH(). However, the functionality remains the same.

SQL Length Function

The final and most common method to determine string length is the length() function. The function accepts a string or byte type. It then returns the length of the input value in characters (for a string) or bytes (for byte type).

The function syntax is as shown:

LENGTH(VALUE)

We can illustrate example usage as shown below:

SELECT
  LENGTH('Hello world') AS LENGTH;

The resulting output is as shown:

LENGTH
11

Closing

This article discusses three main methods you can use to determine the length of a string in Standard SQL.



from https://ift.tt/BvrYe82

Post a Comment

0 Comments