Order By Length of Column in MySQL

MySQLMySQLi Database

<p>To order by length of column in MySQL, use ORDER BY LENGTH.</p><p>Let us first create a table &minus;</p><pre class="result notranslate">mysql&gt; create table DemoTable715 (UserMessage varchar(100)); Query OK, 0 rows affected (0.56 sec)</pre><p>Insert some records in the table using insert command &minus;</p><pre class="result notranslate">mysql&gt; insert into DemoTable715 values(&#39;Aw&#39;); Query OK, 1 row affected (0.49 sec) mysql&gt; insert into DemoTable715 values(&#39;Awe&#39;); Query OK, 1 row affected (0.13 sec) mysql&gt; insert into DemoTable715 values(&#39;A&#39;); Query OK, 1 row affected (0.19 sec) mysql&gt; insert into DemoTable715 values(&#39;Awes&#39;); Query OK, 1 row affected (0.18 sec) mysql&gt; insert into DemoTable715 values(&#39;Awesom&#39;); Query OK, 1 row affected (0.16 sec) mysql&gt; insert into DemoTable715 values(&#39;Awesome&#39;); Query OK, 1 row affected (0.19 sec)</pre><p>Display all records from the table using select statement &minus;</p><pre class="prettyprint notranslate">mysql&gt; select *from DemoTable715;</pre><p>This will produce the following output -</p><pre class="result notranslate">+-------------+ | UserMessage | +-------------+ | Aw | | Awe | | A | | Awes | | Awesom | | Awesome | +-------------+ 6 rows in set (0.00 sec)</pre><p>Following is the query to order by length of column &minus;</p><pre class="prettyprint notranslate">mysql&gt; select *from DemoTable715 order by length(UserMessage);</pre><p>This will produce the following output -</p><pre class="result notranslate">+-------------+ | UserMessage | +-------------+ | A &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | Aw &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| | Awe &nbsp; &nbsp; &nbsp; &nbsp; | | Awes &nbsp; &nbsp; &nbsp; &nbsp;| | Awesom &nbsp; &nbsp; &nbsp;| | Awesome &nbsp; | +-------------+ 6 rows in set (0.00 sec)</pre>
raja
Updated on 22-Aug-2019 07:12:25

Advertisements