Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
ORDERBY word in MySQL?
To order by word in MySQL, you need to use ORDER BY FIELD(). Let us first create a table −
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20), StudentFavouriteSubject varchar(100) ); Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Larry','Java');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Sam','C');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Bob','MongoDB');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('David','MySQL');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement;
mysql> select *from DemoTable;
This will produce the following output −
+-----------+------------------+-------------------------+ | StudentId | StudentFirstName | StudentFavouriteSubject | +-----------+------------------+-------------------------+ | 1 | Larry | Java | | 2 | Sam | C | | 3 | Bob | MongoDB | | 4 | David | MySQL | +-----------+------------------+-------------------------+ 4 rows in set (0.00 sec)
Following is the query to ORDER BY word in MySQL −
mysql> select *from DemoTable ORDER BY FIELD(`StudentFavouriteSubject`, 'MongoDB','MySQL','Java','C');
This will produce the following output −
+-----------+------------------+-------------------------+ | StudentId | StudentFirstName | StudentFavouriteSubject | +-----------+------------------+-------------------------+ | 3 | Bob | MongoDB | | 4 | David | MySQL | | 1 | Larry | Java | | 2 | Sam | C | +-----------+------------------+-------------------------+ 4 rows in set (0.03 sec)
Advertisements
