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
-
Economics & Finance
Selected Reading
MySQL query to order records but fix a specific name and display rest of the values (only some) random
For this, you can use ORDER BY RAND() with LIMIT. Let us first create a −
mysql> create table DemoTable1426 -> ( -> FirstName varchar(20) -> ); Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1426 values('John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1426 values('Adam');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1426 values('Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1426 values('David');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1426 values('Sam');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select −
mysql> select * from DemoTable1426;
This will produce the following output −
+-----------+ | FirstName | +-----------+ | John | | Adam | | Robert | | David | | Sam | +-----------+ 5 rows in set (0.00 sec)
Following is the query to order records but fix a specific name and display rest of the values (only some) random −
mysql> select * from DemoTable1426 order by (FirstName='Robert') desc,RAND() -> limit 3;
This will produce the following output −
+-----------+ | FirstName | +-----------+ | Robert | | Adam | | David | +-----------+ 3 rows in set (0.52 sec)
Advertisements
