Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I am using MSSQL Server 2005. In my db, I have a table "customerNames" which has two columns "Id" and "Name" and approx. 1,000 results.

I am creating a functionality where I have to pick 5 customers randomly every time. Can anyone tell me how to create a query that will get random 5 rows (Id, and Name) every time when a query is executed?

1 Answer

0 votes
by (40.7k points)

Following queries are used to select a random row in SQL:

  • Select a random row with MySQL like this:

QUERY

SELECT column FROM table

ORDER BY RAND()

LIMIT 1

  • Select a random row with PostgreSQL in this way:

QUERY

SELECT column FROM table

ORDER BY RANDOM()

LIMIT 1

  • Select a random row with Microsoft SQL Server in this way:

QUERY

SELECT TOP 1 column FROM table

ORDER BY NEWID()

  • Select a random row with IBM DB2 like this:

QUERY

SELECT column, RAND() as IDX 

FROM table 

ORDER BY IDX FETCH FIRST 1 ROWS ONLY

  • Select a random record with Oracle in this way:

QUERY

SELECT column FROM

( SELECT column FROM table

ORDER BY dbms_random.value )

WHERE rownum = 1

  • Select a random row with SQLite like this:

QUERY

SELECT column FROM table 

ORDER BY RANDOM() LIMIT 1

Or 

  • You can try using the below query :

SELECT TOP 5 Id, Name 

FROM customerNames

ORDER BY NEWID()

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 4, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...