Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the average string length in mysql?

Tags:

sql

mysql

This:

SELECT AVG(LENGTH(string)) 
  FROM BLAH 
 LIMIT 10;

...seems to grind through all results. If I take off the AVG, it's way faster. Is it best to create a subquery like

SELECT AVG(len) 
  FROM (SELECT LENGTH(string) as len 
          FROM BLAH 
         LIMIT 10) as herp

This also seems slow. I don't want to load it all into php loop through with strlen. I was hoping there was a memory efficient solution.

like image 228
ForeverConfused Avatar asked Dec 11 '10 03:12

ForeverConfused


People also ask

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

MySQL LENGTH() Function The LENGTH() function returns the length of a string (in bytes).

How do you find the average in MySQL?

You use the DISTINCT operator in the AVG function to calculate the average value of the distinct values. For example, if you have a set of values 1,1,2,3, the AVG function with DISTINCT operator will return 2 i.e., (1 + 2 + 3) / 3 .

How do I count character length in MySQL?

MySQL CHAR_LENGTH() function MySQL CHAR_LENGTH() returns the length (how many characters are there) of a given string. The function simply counts the number characters and ignore whether the character(s) are single-byte or multi-byte.

Is there LEN function in MySQL?

What's the LEN() Equivalent in MySQL? In SQL Server, you can use the LEN() function to return the number of characters in a string. This is a Transact-SQL function that can also be used in Azure databases. In MySQL, you need to use the CHAR_LENGTH() function.


1 Answers

the first query loops through all the rows in the table (the limit 10 doest limit anything, since there will always be only 1 row returned)

the second query avg's rows 1 to 10

what kind of average are you looking for?

like image 82
The Scrum Meister Avatar answered Oct 31 '22 17:10

The Scrum Meister