- 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 order by the first number in a set of numbers?
To order by the first number in a set of numbers, use ORDER BY SUBSTRING_INDEX(). Let us first create a table −
mysql> create table DemoTable ( SetOfNumbers text ); Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('245,654,76,89,98'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('2000,567,9090,6789'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('1001,90595,657,99'); Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------------+ | SetOfNumbers | +--------------------+ | 245,654,76,89,98 | | 2000,567,9090,6789 | | 1001,90595,657,99 | +--------------------+ 3 rows in set (0.00 sec)
Following is the query to order by the first number in a set of numbers −
mysql> select *from DemoTable order by cast(substring_index(SetOfNumbers,',',1) as unsigned);
This will produce the following output −
+--------------------+ | SetOfNumbers | +--------------------+ | 245,654,76,89,98 | | 1001,90595,657,99 | | 2000,567,9090,6789 | +--------------------+ 3 rows in set (0.00 sec)
Advertisements