Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Determine longest VarChar length

Tags:

mysql

varchar

I am trying to optimize my database. In order to do so, I need to be able to determine the longest data entry in a varchar column, and then trim the column definition to just above that.

How can I find out, using sql, the length of the longest varchar entry in my table?

CREATE TABLE `poller_output` (
  `local_data_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  `rrd_name` varchar(19) NOT NULL DEFAULT '',
  `time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `output` varchar(200) NOT NULL DEFAULT '',
  PRIMARY KEY (`local_data_id`,`rrd_name`,`time`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8
like image 331
Jericon Avatar asked Oct 28 '11 09:10

Jericon


People also ask

How do I find the maximum length of a string in MySQL?

To work out the length of the largest string in a MySQL table, combine the LENGTH() and MAX() functions together like so: SELECT MAX(LENGTH(field_to_query)) FROM table_to_query; where "field_to_query" is the fieldname you want to query and table_to_query is the table.

How do I find the maximum length of a column in MySQL?

Learn MySQL from scratch for Data Science and Analytics Before MySQL 5.03 the value of n can be in the range of 0 to 255 but in and after MySQL 5.03 the value can be in the range of 0 to 65,535. The maximum number of characters stored in VARCHAR depends upon maximum row size and character set used.

How do I find the shortest and longest string in MySQL?

The shortest firstName :(SELECT min(len(<string_column>)) FROM<table_name> ) ; Example : SELECT TOP 1 * FROM friends WHERE len(firstName) = (SELECT min(len(firstName)) FROM friends);

How long is 255 VARCHAR?

VARCHAR(255) stores 255 characters, which may be more than 255 bytes.


2 Answers

If you want to know the max length of the field output, for example, you can use this query:

SELECT Max(CHAR_LENGTH(`output`)) AS Max FROM `poller_output`
like image 131
Aurelio De Rosa Avatar answered Oct 06 '22 21:10

Aurelio De Rosa


You can do this by using the following statement

SELECT column_name FROM database.table PROCEDURE ANALYSE(1,1);

The Max_length value of the results from this will give you the longest varchar in that column.

So in this case assuming you want to investigate the output column then you can run the following

SELECT output FROM poller_output PROCEDURE ANALYSE(1,1);

The advantage of this is that it will also give you the optimal fieldtype in the return values which will be something along the lines of

VARCHAR(56) NOT NULL
like image 31
whudson05 Avatar answered Oct 06 '22 23:10

whudson05