- 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
MySQL query to display records ordered by numeric difference?
Use ORDER BY and set the difference to display records ordered by numeric difference. Following is the syntax −
select *from yourTableName order by (yourIntegerColumnName1 - yourIntegerColumnName2);
Let us first create a table −
mysql> create table DemoTable1313 -> ( -> Name varchar(20), -> Score1 int, -> Score2 int -> ); Query OK, 0 rows affected (3.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1313 values('Chris',40,60); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable1313 values('David',70,50); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1313 values('Adam',35,30); Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1313;
Output
+-------+--------+--------+ | Name | Score1 | Score2 | +-------+--------+--------+ | Chris | 40 | 60 | | David | 70 | 50 | | Adam | 35 | 30 | +-------+--------+--------+ 3 rows in set (0.00 sec)
Following is the query to order by numeric difference −
mysql> select *from DemoTable1313 -> order by (Score1-Score2);
Output
+-------+--------+--------+ | Name | Score1 | Score2 | +-------+--------+--------+ | Chris | 40 | 60 | | Adam | 35 | 30 | | David | 70 | 50 | +-------+--------+--------+ 3 rows in set (0.00 sec)
Advertisements