Syntax error How to get the longest VarChar length in MySQL?

How to get the longest VarChar length in MySQL?



To get the longest varchar length, you need to use CHAR_LENGTH().

The syntax is as follows

SELECT Max(CHAR_LENGTH(yourColumnName)) AS anyAliasName FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table CharLengthDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Sentence varchar(255)
   - > );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into CharLengthDemo(Sentence) values('Java is an object oriented programming language'
- > );
Query OK, 1 row affected (0.45 sec)
mysql> insert into CharLengthDemo(Sentence) values('MySQL is a Relational Database Management System');
Query OK, 1 row affected (0.26 sec)
mysql> insert into CharLengthDemo(Sentence) values('JSP uses Java Programming Language');
Query OK, 1 row affected (0.24 sec)
mysql> insert into CharLengthDemo(Sentence) values('Object is a root class in java');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from CharLengthDemo;

The following is the output

+----+--------------------------------------------------+
| Id | Sentence                                         |
+----+--------------------------------------------------+
|  1 | Java is an object oriented programming language  |
|  2 | MySQL is a Relational Database Management System |
|  3 | JSP uses Java Programming Language               |
|  4 | Object is a root class in java                   |
+----+--------------------------------------------------+
4 rows in set (0.00 sec)

Here is the query to get the longest varchar length

mysql> SELECT Max(CHAR_LENGTH(Sentence)) AS MAXLENGTH FROM CharLengthDemo;

The following is the output displaying the value with the longest varchar length

+-----------+
| MAXLENGTH |
+-----------+
|        48 |
+-----------+
1 row in set (0.00 sec)
Updated on: 2019-07-30T22:30:25+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements