Select three random records with a fixed number of characters for each column value in MySQL

MySQLMySQLi Database

For this, you can use CHAR_LENGTH(). Use RAND() for random records. Let us first create a table −

mysql> create table DemoTable (Subject text);
Query OK, 0 rows affected (0.61 sec)

Example

Insert some records in the table using insert command −

mysql> insert into DemoTable values('C');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('MySQL');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('MongoDB');
Query OK, 1 row affected (0.59 sec)
mysql> insert into DemoTable values('RubyOnRails');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('C++');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Python');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-------------+
| Subject     |
+-------------+
| C           |
| MySQL       |
| Java        |
| MongoDB     |
| RubyOnRails |
| C++         |
| Python      |
+-------------+
7 rows in set (0.00 sec)

Following is the query to select 3 random records with fixed number of characters for each −

mysql> select *from
(select *from DemoTable WHERE CHAR_LENGTH(Subject) = 7 ORDER BY RAND() LIMIT 1 ) tbl
UNION
(select *from DemoTable WHERE CHAR_LENGTH(Subject) = 11 ORDER BY RAND() LIMIT 1 )
UNION
(select *from DemoTable WHERE CHAR_LENGTH(Subject) = 5 ORDER BY RAND() LIMIT 1 );

Output

+-------------+
| Subject     |
+-------------+
| MongoDB     |
| RubyOnRails |
| MySQL       |
+-------------+
3 rows in set (0.04 sec
raja
Published on 20-Aug-2019 09:15:21
Advertisements