SQL - SELECT RANDOM - GeeksforGeeks (2024)

RANDOM( ) in SQL is generally used to return a random row from a table present in the database. It has many applications in real life.

For example :

  1. There are a lot of employees in an organization. Suppose, if the event manager wants to mail any ten random employees then he/she can use the RANDOM( ) in SQL to get the Email Id of the ten random employees.
  2. It can also be used to display random questions during an online exam or MCQ from a pool of questions.

In this article, we are going to discuss how RANDOM( ) can be used using a sample table shown below.

Sample Input Table :

Customer Information
Customer IDCustomer NameE-Mail Address
1Srishtiabc@gmail.com
2Rajdeepdef@gmail.com
3Amanxxx@gmail.com
4Poojaxyz@gmail.com

BASIC SQL QUERY :

1. Creating a Database

CREATE DATABASE database_name;

2. Creating a Table

CREATE TABLE Table_name(col_1 TYPE col_1_constraint,col_2 TYPE col_2 constraint.....)col: Column nameTYPE: Data type whether an integer, variable character, etccol_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc

3. Inserting into a Table

INSERT INTO Table_nameVALUES(val_1, val_2, val_3, ..........)val: Values in particular column

4. View The Table

SELECT * FROM Table_name

Output :

SQL - SELECT RANDOM - GeeksforGeeks (1)

Customer Table

SQL QUERY FOR RANDOM :

1. MYSQL

SELECT col_1,col_2, ... FROM Table_NameORDER BY RAND()col_1 : Column 1col_2 : Column 2

The above query will return the entire table for the specific columns mentioned and the rows will be random and changing position every time we run the query. To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly.

SELECT col_1,col_2, ... FROM Table_NameORDER BY RAND()LIMIT 1col_1 : Column 1col_2 : Column 2

2. PostgreSQL and SQLite

It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).

SELECT col_1,col_2, ... FROM Table_NameORDER BY RAND()LIMIT 1col_1 : Column 1col_2 : Column 2

Output :

SQL - SELECT RANDOM - GeeksforGeeks (2)

Random Rows

SQL - SELECT RANDOM - GeeksforGeeks (3)

RANDOM ROWS

SQL - SELECT RANDOM - GeeksforGeeks (5)

RANDOM ROW

SQL - SELECT RANDOM - GeeksforGeeks (6)

RANDOM ROW

We can observe that the above queries return the rows randomly from all the set of rows in the table. The RANDOM( ) clause is beneficial when there are humongous records in the database.


Last Updated : 21 Jul, 2021

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment...

SQL - SELECT RANDOM - GeeksforGeeks (2024)

FAQs

How to get only 5 results in SQL? ›

Use the SQL LIMIT clause with ORDER BY statement

Here, I have added the ORDER BY clause on the Employee_last_name column and then specified LIMIT 5 to display the first 5 rows in the specified order. LIMIT 5; I have executed the above query and got the below output.

Can you SELECT a random sample in SQL? ›

Now let's find how to do Random Sampling within Groups in SQL using RAND() function. Below SQL statement is to display rows in random order using RAND() function: Query: SELECT * FROM table_name order by RANDOM();

How to SELECT random value from SQL? ›

SQL SELECT RANDOM
  1. SELECT column FROM table ORDER BY RAND ( ) LIMIT 1.
  2. SELECT TOP 1 column FROM table ORDER BY NEW ID()
  3. SELECT column FROM (SELECT column FROM table ORDER BY dbms_random.value) WHERE rownum =1.
  4. SELECT column FROM table ORDER BY RAND() LIMIT 1.

How do I SELECT a random row in MySQL? ›

The primary method for achieving random selection in MySQL is through the RAND() function. This function generates a random floating-point value between 0 and 1.

How do I limit search results in SQL? ›

Limiting Rows in a MySQL Result Set in SQL

To to limit the number of rows in a MySQL result set, use the LIMIT clause. This clause takes two arguments: the number of rows to return, and an optional offset.

What is the difference between fetch and limit? ›

In contrast to the 'LIMIT' clause, the 'FETCH' clause is a part of the 'OFFSET FETCH' clause, which is used in conjunction with the 'ORDER BY' clause. This clause is used to skip a specific number of rows before returning the result set. The 'FETCH' clause then returns a defined number of rows.

How do I get results in random order in SQL? ›

To select rows from a table in a random order, use the ORDER BY RAND() clause. For example: SELECT * FROM your_table ORDER BY RAND(); This query selects all rows from your_table and orders them randomly.

How do you SELECT random sampling? ›

To create a simple random sample, there are six steps: (a) defining the population; (b) choosing your sample size; (c) listing the population; (d) assigning numbers to the units; (e) finding random numbers; and (f) selecting your sample.

What does random () do in SQL? ›

Definition and Usage

The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).

What is the method to SELECT random values from a list? ›

Select a random value from a list using random.

randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list and get the index, and then the corresponding value.

How to SELECT random records from a database? ›

Strategy #1 - Use RANDOM()

The first strategy is to use the database's built-in RANDOM function to select a random record. For PostgreSQL or SQLite, use RANDOM() , and for MySQL or MariaDB, use RAND() .

Is limit random in SQL? ›

The LIMIT clause randomly picks rows to be returned unless ORDER BY clause exists together with the LIMIT clause. In other words, the ORDER BY as well as the LIMIT clause must be part of the same SQL statement and not like the case where one is part of main query and other is part of subquery.

How to SELECT random number from range in MySQL? ›

RAND() Function in MySQL. The RAND() function in MySQL is used to a return random floating-point value V in the range 0 <= V < 1.0. If we want to obtain a random integer R in the range i <= R < j, we have to use the expression : FLOOR(i + RAND() * (j − i)).

How do I SELECT a specific row number in SQL? ›

This can be done by assigning the ROW_NUMBER() function to each row of data and then using the Partition clause to group the data by a specific value. The Nth highest value can then be determined by using the ORDER BY clause to sort the data in descending order and determine the value of the Nth row.

How to order by random in MySQL? ›

To do so, we need to execute the following query: mysql> SELECT * FROM items ORDER BY RAND ();

How do I get the last 5 records in SQL? ›

1 Answer. ORDER BY id ASC; In the above query, we used subquery with the TOP clause that returns the table with the last 5 records sorted by ID in descending order. Again, we used to order by clause to sort the result-set of the subquery in ascending order by the ID column.

How to limit the number of rows returned in SQL? ›

SQL Server provides a simple way to limit the number of rows returned by a query using the TOP keyword. The TOP keyword allows you to specify the number of rows you want to retrieve from a query.

How to SELECT only a certain number of rows in SQL? ›

The LIMIT , SELECT TOP or ROWNUM command is used to specify the number of records to return. Note: SQL Server uses SELECT TOP .

How to insert 5 values in SQL? ›

If you want to insert many rows into a SQL table, you have to repeat INSERT INTO over and over in separate statements. INSERT INTO Person VALUES (1, "Amir"); INSERT INTO Person VALUES (2, "Sofia"); INSERT INTO Person VALUES (3, "Aya"); ...

Top Articles
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 6182

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.