Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char_length not working as thought

Tags:

mysql

Below is what I have

+++++++++++++++
+ id + myData +
+++++++++++++++
+ 1  + ABCD   +
+ 2  + ABCDD  +
+++++++++++++++

When I execute

select char_length((select myData from mytable where id = 1)) as MyLength;

I get result as

++++++++++++
+ MyLength +
++++++++++++
+  4       +
++++++++++++

But when I execute query,

select char_length((select myData from mytable) as MyLength;

I get error as

DDL and DML statements are not allowed in the query panel for MySQL; only SELECT statements are allowed.

Demo

like image 329
Fahim Parkar Avatar asked Aug 31 '25 18:08

Fahim Parkar


1 Answers

You are wrapping the entire query output in CHAR_LENGTH(). When applying the WHERE id = 1 to the subquery, it returns a single row, and since you've selected a single column, you get one single string value back which CHAR_LENGTH() will accept as its argument.

If the subquery select mySata from mytable returns multiple rows, char_length() cannot accept it as an input. Instead, merely apply CHAR_LENGTH() to myData in a regular SELECT statement to see the lengths of multiple rows.

SELECT CHAR_LENGTH(myData) AS myLength FROM mytable
like image 135
Michael Berkowski Avatar answered Sep 02 '25 06:09

Michael Berkowski