Summary -

In this topic, we described about the Select Random with detailed example.

SELECT RANDOM statement used to fetch random rows from existing table. SELECT RANDOM statement have different syntaxes for different database are listed below.

Syntax for Select Random in MySQL -

SELECT column FROM table
ORDER BY RAND() LIMIT limit_number; 

Syntax for Select Random in Microsoft SQL Server -

SELECT TOP 1 column FROM Table_name
ORDER BY NEW ID(); 

Syntax for Select Random in Oracle –

 SELECT column FROM 
(SELECT column FROM table 
ORDER BY dbms_random.value) 
WHERE rownum = row_number; 

Syntax for Select Random in MY SQL –

SELECT column FROM table
ORDER BY RANDOM() LIMIT limit_number; 

Syntax for Select Random in SQLite –

SELECT column FROM table
ORDER BY RANDOM() LIMIT limit_number; 

Select Random used in real examples –

  • SELECT RANDOM used to provide random captcha while we want to log-in in an application.
  • SELECT RANDOM used in Online Exams of students to appear random questions.
  • SELECT RANDOM used in Web pages that to appear random pictures.
  • SELECT RANDOM used to provide security in Some applications.

Example

Let us consider below table(s) as an example table(s) to frame the SQL query for getting the desired results.

employee_details -

emp_id emp_name designation manager_id date_of_hire salary dept_id
001 Employee1 Director 2019-07-11 45000.00 1000
002 Employee2 Director 2019-07-11 40000.00 2000
003 Employee3 Manager Employee1 2019-07-11 27000.00 1000
004 Employee4 Manager Employee2 2019-10-08 25000.00 2000
005 Employee5 Analyst Employee3 2019-07-11 20000.00 1000
006 Employee6 Analyst Employee3 2019-10-08 18000.00 1000
007 Employee7 Clerk Employee3 2019-07-11 15000.00 1000
008 Employee8 Salesman Employee4 2019-09-09 14000.00 2000
009 Employee9 Salesman Employee4 2019-10-08 13000.00 2000

Scenario – Fetch 5 random rows from table.

Requirement – Fetch 5 random rows from employee_details table. The query was as follows –

SELECT * FROM employee_details ORDER BY RAND() LIMIT 5; 

By executing above query, we can get output like as shown in below –

emp_id emp_name designation manager_id date_of_hire salary dept_id
001 Employee1 Director 2019-07-11 45000.00 1000
003 Employee3 Manager Employee1 2019-07-11 27000.00 1000
004 Employee4 Manager Employee2 2019-10-08 25000.00 2000
007 Employee7 Clerk Employee3 2019-07-11 15000.00 1000
009 Employee9 Salesman Employee4 2019-10-08 13000.00 2000

Note :- The output may gets varies from execution to execution.