- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Order by a function of two columns in a single MySQL query
Let us first create a table
mysql> create table orderByAFunctionDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstNumber int, -> SecodNumber int -> ); Query OK, 0 rows affected (0.44 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(10,4); Query OK, 1 row affected (0.11 sec) mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(45,78); Query OK, 1 row affected (0.17 sec) mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(23,10); Query OK, 1 row affected (0.12 sec) mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(67,237); Query OK, 1 row affected (0.16 sec) mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(12,90); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from orderByAFunctionDemo;
The following is the output
+----+-------------+-------------+ | Id | FirstNumber | SecondNumber| +----+-------------+-------------+ | 1 | 10 | 4 | | 2 | 45 | 78 | | 3 | 23 | 10 | | 4 | 67 | 237 | | 5 | 12 | 90 | +----+-------------+-------------+ 5 rows in set (0.00 sec)
Here is the query to order by a function of two columns. The query is as follows −
mysql> select (4*FirstNumber+5*SecondNumber) as Calculation -> from orderByAFunctionDemo -> order by Calculation desc;
The following is the output
+-------------+ | Calculation | +-------------+ | 1453 | | 570 | | 498 | | 142 | | 60 | +-------------+ 5 rows in set (0.00 sec)
Advertisements