MySQL ORDER BY with different ordering for some of the values as descending and others ascending?

MySQLMySQLi Database

<p>You can use the field() for this. Let us first create a table &minus;</p><pre class="result notranslate">mysql&gt; create table DemoTable &nbsp; &nbsp;( &nbsp; &nbsp;Value int &nbsp; &nbsp;); Query OK, 0 rows affected (0.80 sec)</pre><p>Insert some records in the table using insert command &minus;</p><pre class="prettyprint notranslate">mysql&gt; insert into DemoTable values(10); Query OK, 1 row affected (0.18 sec) mysql&gt; insert into DemoTable values(70); Query OK, 1 row affected (0.14 sec) mysql&gt; insert into DemoTable values(60); Query OK, 1 row affected (0.14 sec) mysql&gt; insert into DemoTable values(56); Query OK, 1 row affected (0.12 sec) mysql&gt; insert into DemoTable values(81); Query OK, 1 row affected (0.44 sec) mysql&gt; insert into DemoTable values(85); Query OK, 1 row affected (0.15 sec)</pre><p>Display all records from the table using select statement &minus;</p><pre class="prettyprint notranslate">mysql&gt; select *from DemoTable;</pre><h2>Output</h2><pre class="result notranslate">+-------+ | Value | +-------+ | 10 | | 70 | | 60 | | 56 | | 81 | | 85 | +-------+ 6 rows in set (0.00 sec)</pre><p>Following is the query to ORDER BY specific 3 values as descending and rest of the as ascending order &minus;</p><pre class="prettyprint notranslate">mysql&gt; select *from DemoTable order by field(Value,60,70,81) desc;</pre><h2>Output</h2><pre class="result notranslate">+-------+ | Value | +-------+ | 81 | | 70 | | 60 | | 10 | | 56 | | 85 | +-------+ 6 rows in set (0.00 sec)</pre>
raja
Updated on 30-Jul-2019 22:30:26

Advertisements