SQL Cookbook Lesson
How to check the length of a string in SQL
Learn how to check the length of a string in SQL with examples and explanations from SQLPad.
Problem
You need to determine the length of a string in a SQL database.
Sample Data
Consider the following sample table named 'users':
| id | username |
|---|---|
| 1 | john |
| 2 | emily |
| 3 | ann |
MySQL Solution
SELECT username, LENGTH(username) AS string_length
FROM users;
MySQL Explanation
In MySQL, the LENGTH() function is used to find the length of a string. This function returns the length of a string in bytes. In the solution provided, we are selecting the 'username' column and the length of the 'username' for each row in the 'users' table.
PostgreSQL Solution
SELECT username, LENGTH(username) AS string_length
FROM users;
PostgreSQL Explanation
In PostgreSQL, the LENGTH() function is used to determine the length of a string. This function returns the number of characters in the string. In the provided solution, we are selecting the 'username' column and the length of the 'username' for each row in the 'users' table.
Please note that the LENGTH() function in both MySQL and PostgreSQL operates similarly when dealing with string data that only includes single-byte characters. However, for multi-byte characters like those found in various non-English languages, the CHAR_LENGTH() or CHARACTER_LENGTH() function would provide a more accurate count of characters, as LENGTH() would count bytes, not characters.