Here, we are going to see how to find the shortest and longest string from a column of a table in a database with the help of SQL queries. We will first create a database “geeks“, then we create a table “friends” with “firstName“, “lastName“, “age” columns. Then will perform our SQL query on this table to retrieve the shortest and longest string in a column.
For this article, we will be using the MS SQL Server as our database.
Creating a Database :
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Using Database :
USE geeks;
Table Definition:
We have the following Employee table in our geeks database :
CREATE TABLE friends( firstName VARCHAR(30) not NULL, lastName VARCHAR(30) not NULL, age INT NOT NULL);
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS friends;
Adding Data to Table:
Use the below statement to add data to the friends table:
INSERT INTO friends values ('Ajit','Yadav', 20), ('Ajay', 'More', 21), ('Amir', 'Jawadwala', 21), ('Zara', 'Khan', 20), ('Yogesh', 'Vaishnav', 21), ('Ashish', 'Yadav', 21), ('Govind', 'Vaishnav', 22), ('Vishal', 'Vishwakarma', 21);
To verify the contents of the table use the below statement:
SELECT * FROM friends;
Now let’s find the shortest and longest firstName from the table we have just created using char_length(), min(), and max() functions and LIMIT clause.
The shortest firstName :
Use the ow syntax to find the shortest firstName in the friends table:
SYNTAX :
SELECT TOP 1 * FROM<table_name> –Here we want only one row that’s why TOP 1 *
WHERE
len(<string_column>) =
(SELECT min(len(<string_column>)) FROM<table_name> ) ;
Example :
SELECT TOP 1 * FROM friends WHERE len(firstName) = (SELECT min(len(firstName)) FROM friends);
Output :
The row with lexicographically shortest firstName :
If there are more than one strings of the same minimum length, and we want to retrieve, lexicographically, the shortest string then can do as following:
SYNTAX :
SELECT TOP 1 * FROM<table_name> –Here we want only one row that’s why TOP 1*.
WHERE
len(<string_column>) =
(SELECTmin(len(<string_column>)) FROM <table_name> )
ORDER BY <column_name>; –In this case column_name would be firstName.
Example :
SELECT TOP 1 * FROM friends WHERE len(firstName) = (SELECT min(len(firstName)) FROM friends) ORDER BY firstname;
Output :
The row with longest firstName :
SYNTAX :
SELECT TOP 1* FROM<table_name>
WHERE
len(<string_column>) =
(SELECT max(len(<string_column>)) FROM <table_name> );
Example :
SELECT TOP 1 * FROMfriends WHERE len(firstName) = (SELECT max(len(firstName)) FROMfriends);
Output :
The row with lexicographically longest firstName :
SYNTAX :
SELECT TOP 1* FROM<table_name>
WHERE
len(<string_column>) =
(SELECT max(len(<string_column>)) from <table_name> )
ORDER BY <string_column>; –here we would order data by firstName.
Example :
SELECT TOP 1* FROM friends WHERE len(firstName) = (SELECT max(len(firstName)) FROM friends) ORDER BY firstName;
Output :
Last Updated :
13 Apr, 2021
Like Article
Save Article
I’ve a table contains the columns like
Prefix | CR
----------------------------------------
g | ;#WR_1;#WR_2;#WR_3;#WR_4;#
v | ;#WR_3;#WR_4;#
j | WR_2
m | WR_1
d | ;#WR_3;#WR_4;#
f9 | WR_3
I want to retrieve data from CR column WHERE it has the longest text string i.e in current table it is ;#WR_1;#WR_2;#WR_3;#WR_4;#.
I’m using
SELECT max(len(CR)) AS Max_Length_String FROM table1
But it retuns
Max_Length_String
----------------------------------------
26
But what i need is not the length (26), i wanted like this
Max_Length_String
----------------------------------------
;#WR_1;#WR_2;#WR_3;#WR_4;#
ˈvɔlə
8,91610 gold badges63 silver badges88 bronze badges
asked Feb 19, 2014 at 15:38
The easiest way is:
select top 1 CR
from table t
order by len(CR) desc
Note that this will only return one value if there are multiple with the same longest length.
answered Feb 19, 2014 at 15:46
Gordon LinoffGordon Linoff
1.2m57 gold badges639 silver badges779 bronze badges
6
You can:
SELECT CR
FROM table1
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)
Having just recieved an upvote more than a year after posting this, I’d like to add some information.
- This query gives all values with the maximum length. With a TOP 1 query you get only one of these, which is usually not desired.
- This query must probably read the table twice: a full table scan to get the maximum length and another full table scan to get all values of that length. These operations, however, are very simple operations and hence rather fast. With a TOP 1 query a DBMS reads all records from the table and then sorts them. So the table is read only once, but a sort operation on a whole table is quite some task and can be very slow on large tables.
- One would usually add
DISTINCT
to my query (SELECT DISTINCT CR FROM ...
), so as to get every value just once. That would be a sort operation, but only on the few records already found. Again, no big deal. - If the string lengths have to be dealt with quite often, one might think of creating a computed column (calculated field) for it. This is available as of Ms Access 2010. But reading up on this shows that you cannot index calculated fields in MS Access. As long as this holds true, there is hardly any benefit from them. Applying
LEN
on the strings is usually not what makes such queries slow.
answered Feb 19, 2014 at 15:45
Thorsten KettnerThorsten Kettner
87.8k7 gold badges47 silver badges71 bronze badges
1
This was the first result on «longest string in postgres» google search so I’ll put my answer here for those looking for a postgres solution.
SELECT max(char_length(column)) AS Max_Length_String FROM table
postgres docs: http://www.postgresql.org/docs/9.2/static/functions-string.html
answered Jan 25, 2016 at 19:37
tmthyjamestmthyjames
1,5682 gold badges22 silver badges30 bronze badges
3
You can get it like this:
SELECT TOP 1 CR
FROM tbl
ORDER BY len(CR) DESC
but i’m sure, there is a more elegant way to do it
answered Feb 19, 2014 at 15:47
xeraphimxeraphim
4,3359 gold badges51 silver badges98 bronze badges
For Postgres:
SELECT column
FROM table
WHERE char_length(column) = (SELECT max(char_length(column)) FROM table )
This will give you the string itself,modified for postgres from @Thorsten Kettner answer
answered Oct 27, 2016 at 10:07
For Oracle 11g:
SELECT COL1
FROM TABLE1
WHERE length(COL1) = (SELECT max(length(COL1)) FROM TABLE1);
answered Aug 29, 2016 at 23:22
kavehmbkavehmb
9,8021 gold badge19 silver badges22 bronze badges
With two queries you can achieve this. This is for mysql
//will select shortest length coulmn and display its length.
// only 1 row will be selected, because we limit it by 1
SELECT column, length(column) FROM table order by length(column) asc limit 1;
//will select shortest length coulmn and display its length.
SELECT CITY, length(city) FROM STATION order by length(city) desc limit 1;
answered Mar 23, 2017 at 5:46
ShobiShobi
10.1k6 gold badges43 silver badges80 bronze badges
you have to do some changes by applying group by or query with in query.
"SELECT CITY,LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;"
it will return longest cityname from city.
Dilan
2,5707 gold badges23 silver badges32 bronze badges
answered Aug 21, 2020 at 9:39
To answer your question, and get the Prefix
too, for MySQL you can do:
select Prefix, CR, length(CR) from table1 order by length(CR) DESC limit 1;
and it will return
+-------+----------------------------+--------------------+
| Prefix| CR | length(CR) |
+-------+----------------------------+--------------------+
| g | ;#WR_1;#WR_2;#WR_3;#WR_4;# | 26 |
+-------+----------------------------+--------------------+
1 row in set (0.01 sec)
answered Apr 27, 2017 at 11:04
pjammerpjammer
9,4414 gold badges45 silver badges56 bronze badges
In MySQL you can use,
(SELECT CITY,
LENGTH(CITY) AS CHR_LEN
FROM STATION
ORDER BY CHR_LEN ASC,
CITY
LIMIT 1)
UNION
(SELECT CITY,
LENGTH(CITY) AS CHR_LEN
FROM STATION
ORDER BY CHR_LEN DESC,
CITY
LIMIT 1)
David Buck
3,71335 gold badges31 silver badges35 bronze badges
answered Oct 18, 2020 at 3:48
Instead of SELECT max(len(CR)) AS Max_Length_String FROM table1
Use
SELECT (CR) FROM table1
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)
answered Feb 19, 2014 at 15:48
RevanRevan
97411 silver badges25 bronze badges
SELECT w.DEPARTMENT
FROM Worker w
group by w.DEPARTMENT
order by length(w.DEPARTMENT) DESC
LIMIT 2 ;
answered Jan 8, 2022 at 17:11
Hemanth KumarHemanth Kumar
7991 gold badge6 silver badges7 bronze badges
4
In MariaDB only length
and char_length
worked for me.
If you use non-english letters, you better use char_length
.
For example:
select
e.id,
home.name,
LENGTH(home.name) as length,
CHAR_LENGTH(home.name) as char_length
from events e
left join teams home on e.home_id = home.id
order by CHAR_LENGTH(home.name) desc
answered Jan 9, 2022 at 12:59
SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) ASC LIMIT 1;
SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) DESC LIMIT 1;
double-beep
4,96617 gold badges32 silver badges41 bronze badges
answered Jun 3, 2020 at 12:02
If column datatype is text you should use DataLength function like:
select top 1 CR, DataLength(CR)
from tbl
order by DataLength(CR) desc
answered Jul 29, 2020 at 7:13
DevcaDevca
771 silver badge2 bronze badges
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.
Download TablePlus for Mac.
Not on Mac? Download TablePlus for Windows.
On Linux? Download TablePlus for Linux
Need a quick edit on the go? Download TablePlus for iOS
We can use a combination of the MAX and MIN functions in conjunction with the SQL length function to get the max or min character width of a column. As the LENGTH function is universally used in most relational databases, we can use that syntax for our examples. Finding the max or min length of a column in SQL is pretty straight-forward.
SQL Server databases use LEN or DATALENGTH to find field width. It also has its own function to find the maximum length of a column – COL_LENGTH.
Syntax for finding MAX column length for a single field
SELECT MAX(LENGTH(<column_name>)) AS MaxColumnLength FROM Table;
Syntax for finding MIN column length for a single field
SELECT MIN(LENGTH(<column_name>)) AS MinColumnLength FROM Table;
If we include any non-aggregate functions into our query then we need a GROUP BY clause. Also, we could replace the above syntax examples with LEN or DATALENGTH for SQL Server.
RELATED: GROUP BY – Count, Sum, and More
Finding String Length for Multiple Columns
Similarly to finding a single field length we can find multiple column lengths just as easily.
Syntax for finding MAX column length for a multiple fields
SELECT MAX(LENGTH(<column_1>)) AS MaxColLen1, MAX(LENGTH(<column_2>)) AS MaxColLen2 FROM Table;
Syntax for finding MIN column length for multiple fields
SELECT MIN(LENGTH(<column_1>)) AS MinColLen1, MIN(LENGTH(<column_2>)) AS MinColLen2 FROM Table;
Practical Examples of MIN and MAX Field Length
We can see the following practical example shows us how to write the SQL to include two column values.
The resulting output gives us our max string length for both columns. The longest field in our first name column is a length of 13 characters and the max length of our last name column is 12 characters.
Alternatively, we could also get the minimum values with the following sql syntax.
In this case our minimum values output for first name is 3 and last name is a length of 4.
Final Thoughts
Finding the max and min lengths of a column in sql can be very useful. This is especially true when data modeling for a new database and migrating data from another system. These functions provide us valuable information for data analysis as well. Just don’t forget to include GROUP BY clause if you decide to add in non-aggregate columns into your queries.
Как найти самую длинную строку в данных столбца таблицы
У меня в таблице есть такие столбцы, как
Prefix | CR
----------------------------------------
g | ;#WR_1;#WR_2;#WR_3;#WR_4;#
v | ;#WR_3;#WR_4;#
j | WR_2
m | WR_1
d | ;#WR_3;#WR_4;#
f9 | WR_3
Я хочу получить данные из столбца CR, ГДЕ у него самая длинная текстовая строка, т.е. в текущей таблице это ; # WR_1; # WR_2; # WR_3; # WR_4; #. я использую
SELECT max(len(CR)) AS Max_Length_String FROM table1
Но это возвращает
Max_Length_String
----------------------------------------
26
Но мне нужна не длина (26), я хотел вот так
Max_Length_String
----------------------------------------
;#WR_1;#WR_2;#WR_3;#WR_4;#
2014-02-19 15:38
15
ответов
Решение
Самый простой способ это:
select top 1 CR
from table t
order by len(CR) desc
Обратите внимание, что это вернет только одно значение, если есть несколько с одинаковой длинной длиной.
2014-02-19 15:46
Вы можете:
SELECT CR
FROM table1
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)
Я только что получил ответ более чем через год после публикации, я хотел бы добавить некоторую информацию.
- Этот запрос дает все значения с максимальной длиной. С запросом TOP 1 вы получаете только один из них, что обычно нежелательно.
- Этот запрос, вероятно, должен прочитать таблицу дважды: полное сканирование таблицы, чтобы получить максимальную длину, и еще одно полное сканирование таблицы, чтобы получить все значения этой длины. Эти операции, однако, очень простые и, следовательно, довольно быстрые. С помощью запроса TOP 1 СУБД считывает все записи из таблицы и затем сортирует их. Таким образом, таблица читается только один раз, но операция сортировки для всей таблицы является довольно сложной задачей и может быть очень медленной для больших таблиц.
- Можно было бы добавить
DISTINCT
на мой запрос (SELECT DISTINCT CR FROM ...
), чтобы получить каждое значение только один раз. Это будет операция сортировки, но только на нескольких найденных записях. Опять же, ничего страшного. - Если с длинами строк приходится иметь дело довольно часто, можно подумать о создании вычисляемого столбца (вычисляемого поля) для него. Это доступно с Ms Access 2010. Но чтение этого показывает, что вы не можете индексировать вычисляемые поля в MS Access. Пока это верно, от них вряд ли что-то выиграет. применение
LEN
на строки обычно не то, что делает такие запросы медленными.
2014-02-19 15:45
Вы можете получить это так:
SELECT TOP 1 CR
FROM tbl
ORDER BY len(CR) DESC
но я уверен, что есть более элегантный способ сделать это
2014-02-19 15:47
Для Postgres:
SELECT column
FROM table
WHERE char_length(column) = (SELECT max(char_length(column)) FROM table )
Это даст вам саму строку, модифицированную для postgres от @Thorsten Kettner answer
2016-10-27 10:07
Для Oracle 11g:
SELECT COL1
FROM TABLE1
WHERE length(COL1) = (SELECT max(length(COL1)) FROM TABLE1);
2016-08-29 23:22
С двумя запросами вы можете достичь этого. Это для MySQL
//will select shortest length coulmn and display its length.
// only 1 row will be selected, because we limit it by 1
SELECT column, length(column) FROM table order by length(column) asc limit 1;
//will select shortest length coulmn and display its length.
SELECT CITY, length(city) FROM STATION order by length(city) desc limit 1;
2017-03-23 05:46
Вам нужно внести некоторые изменения, применив group by или query with in query.
"SELECT CITY,LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;"
он вернет самое длинное название города из города.
2020-08-21 12:39
Только в MariaDB
length
и работал на меня.
Если вы используете неанглийские буквы, вам лучше использовать
char_length
. Например:
select
e.id,
home.name,
LENGTH(home.name) as length,
CHAR_LENGTH(home.name) as char_length
from events e
left join teams home on e.home_id = home.id
order by CHAR_LENGTH(home.name) desc
2022-01-09 12:59
Вместо SELECT max(len(CR)) AS Max_Length_String FROM table1
использование
ВЫБРАТЬ (CR) ИЗ таблицы1
ГДЕ len(CR) = (ВЫБЕРИТЕ макс. (Len (CR)) ИЗ таблицы1)
2014-02-19 15:48
SELECT w.DEPARTMENT
FROM Worker w
group by w.DEPARTMENT
order by length(w.DEPARTMENT) DESC
LIMIT 2 ;
2022-01-08 17:11
Чтобы ответить на ваш вопрос, и получить Prefix
также для MySQL вы можете сделать:
select Prefix, CR, length(CR) from table1 order by length(CR) DESC limit 1;
и он вернется
+-------+----------------------------+--------------------+
| Prefix| CR | length(CR) |
+-------+----------------------------+--------------------+
| g | ;#WR_1;#WR_2;#WR_3;#WR_4;# | 26 |
+-------+----------------------------+--------------------+
1 row in set (0.01 sec)
2017-04-27 11:04
В MySQL вы можете использовать,
(SELECT CITY,
LENGTH(CITY) AS CHR_LEN
FROM STATION
ORDER BY CHR_LEN ASC,
CITY
LIMIT 1)
UNION
(SELECT CITY,
LENGTH(CITY) AS CHR_LEN
FROM STATION
ORDER BY CHR_LEN DESC,
CITY
LIMIT 1)
2020-10-18 06:48
SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) ASC LIMIT 1;
SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) DESC LIMIT 1;
2020-06-03 15:02
Если тип данных столбца — текст, вы должны использовать функцию DataLength, например:
select top 1 CR, DataLength(CR)
from tbl
order by DataLength(CR) desc
2020-07-29 10:13