Link to home
Start Free TrialLog in
Avatar of mmalik15
mmalik15

asked on

how to select random recods or rows from sql server table including row no

My sql query is below

SELECT top 24 ROW_NUMBER() OVER (ORDER BY QuestionID) AS QuestionNo, Q.QuestionID From Questions Q
ORDER BY NEWID()

The first part " top 24 ROW_NUMBER() OVER (ORDER BY QuestionID) AS QuestionNo" gives me a row no. This part "ORDER BY NEWID()" gives me random rows. The results are like below

QuestionNo      QuestionID
2      aa
3      ss
1      qq


The above query first adds row no column to the other columns and then pulls the random records whereas I want the random questions first and then added row number to them e.g.

QuestionNo      QuestionID
1      aa
2      ss
3      qq

Avatar of venk_r
venk_r
Flag of United States of America image

You dont need to use order by NEWID() function.You willl get the desired result without using it as it will order by using the function by itself.
Avatar of Kevin Cross
You probably meant something more like this:

SELECT top 24 ROW_NUMBER() OVER (ORDER BY NEWID()) AS QuestionNo, Q.QuestionID
FROM Questions Q
ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thats correct. I should have sent the corrected sql .
what about

select top 24 * from (
select *, newid() myid from mytable
) order by myid
HainKurt, myid will be a UNIQUEIDENTIFIER in that case and not a sequential 1-24.
got it :) what about this?

select top 24 *, row_number() over(order by myid) rowNo  from (
select *, newid() myid from mytable
) order by myid
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
the query above adds newid to all rows, then order by this and add row numbers, then we select top 24

if it is same/similar to yours above, just ignore it :)
Avatar of mmalik15
mmalik15

ASKER

Excellent guys!