How to find the longest string value in a column SQL?
Syntax
There are several ways to get the longest string value of a specified column in SQL.
You can sort the table using the LENGTH of that column then select the first row with longest string value:
SELECT *
FROM table_name
ORDER BY LENGTH(col_name) DESC
LIMIT 1;
Or use the MAX() function:
SELECT *
FROM table_name
WHERE LENGTH(col_name) = (
SELECT MAX(LENGTH(col_name))
FROM table_name)
LIMIT 1;
If there are possibly more than one rows with same longest string values and you want to return them all:
SELECT *
FROM table_name
WHERE LENGTH(col_name) = (
SELECT MAX(LENGTH(col_name))
FROM table_name);
Example:
We have this table departments
in MySQL:
dept_no | dept_name |
---|---|
d001 | Marketing |
d002 | Finance |
d003 | Human Resources |
d004 | Production |
d005 | Development |
d006 | Quality Management |
d007 | Sales |
d008 | Research |
d009 | Customer Service |
Now get the row with the longest department name:
SELECT *
FROM departments
WHERE LENGTH(dept_name) = (
SELECT MAX(LENGTH(dept_name))
FROM departments);
The result is:
dept_no | dept_name |
---|---|
d006 | Quality Management |
Need a good GUI tool for databases? TablePlus provides a native client that allows you to access and manage Oracle, MySQL, SQL Server, PostgreSQL, and many other databases simultaneously using an intuitive and powerful graphical interface.
Not on Mac? Download TablePlus for Windows.
On Linux? Download TablePlus for Linux
Need a quick edit on the go? Download TablePlus for iOS