Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select 20 random questions from each set in sql?

I am working on online question application.

I am Fetching Records from a database.

I have SQL database holding 1000 question in 10 set. I mean each set containing 100 questions. How can I take 20 random questions from each set? I mean how can I select 2 (as per request) random question from each set?

like image 382
ssg Avatar asked Dec 19 '12 06:12

ssg


People also ask

How do you select a random sample in SQL?

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. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).

Which command is used to select 50% rows randomly?

The SQL SELECT RANDOM() function returns the random row.

How do I randomize SQL results?

Whenever we need to sort a given SQL query result set, we have to use the ORDER BY clause. However, to randomize the returned rows, we need the ORDER BY clause to use a function or database object that returns a random value for each row contained in the SQL result set.


3 Answers

Try:

SELECT TOP 20 * FROM [YourTable] ORDER By NEWID()

More About NEWID().

like image 185
4b0 Avatar answered Oct 31 '22 02:10

4b0


If you need to get 20 random questions from each group here is an SQLFiddle example. SetNum here is a set ID

select * from 
(
select t.*, 
ROW_NUMBER() 
over (partition by setNum order by NewId()) rNum from t
) t2 where rNum<=20
like image 42
valex Avatar answered Oct 31 '22 00:10

valex


Try this if you want 2 random questions from each SET...

SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 1) ORDER By NEWID()
UNION
SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 2) ORDER By NEWID()
UNION
.
.
.
.
UNION
SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 10) ORDER By NEWID()
like image 31
Adeel Ahmed Avatar answered Oct 31 '22 01:10

Adeel Ahmed