

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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)
- Related Questions & Answers
- Set a certain value first with MySQL ORDER BY?
- ORDER BY alphabet first then follow by number in MySQL?
- MySQL query to order by NULL values
- Order by number of chars in MySQL?
- MySQL query to first set negative value in descending order and then positive value in ascending order
- MySQL query to select a row which contains same number in a column with set of numbers separated by comma?
- Order MySQL query by multiple ids?
- MySQL order by string with numbers?
- MySQL query to select distinct order by id
- Order by a function of two columns in a single MySQL query
- ORDER BY specific field value first in MySQL
- MySQL query to ORDER BY records on the basis of modulus result
- Order by on a specific number in MySQL?
- Wrap around to first value and implement MySQL ORDER BY ASC and DESC in a single query
- How to ORDER BY FIELD with GROUP BY in a single MySQL query?
Advertisements