MySQL LENGTH() Function
The LENGTH()
function in MySQL calculates the length of a string, returning the number of bytes the string occupies. This is important because the number of bytes can differ from the number of characters, particularly when dealing with multi-byte character sets.
LENGTH(): Definition and Usage
LENGTH()
is used to determine the size of strings in bytes. This can be essential for tasks such as data validation, string formatting, or operations that depend on string length. Keep in mind that a single character might use more than one byte depending on the character set (UTF-8, for example, uses multiple bytes per character for many characters).
Syntax
Syntax
LENGTH(string)
Parameter Values
Parameter | Description |
---|---|
string |
The string whose length you want to determine. This is required. |
Examples
Finding the Length of a String Literal
This example finds the length (in bytes) of the string "SQL Tutorial".
Syntax
SELECT LENGTH("SQL Tutorial") AS LengthOfString;
Output
12
Finding the Length of Strings in a Column
This example shows how to get the length (in bytes) of each 'CustomerName' from the 'Customers' table (assuming a table named 'Customers' exists with a 'CustomerName' column).
Syntax
SELECT LENGTH(CustomerName) AS LengthOfName
FROM Customers;
Output
LengthOfName
-------------
(The length, in bytes, of each customer name from the Customers table will be displayed here.)