Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a Random Subset in SQL (Sybase Server IQ)

Tags:

sql

random

sap-iq

I'm trying to select a random subset of records using either rand() or newid(), but any time I run the following, I always get the same results back:

SELECT *,rand() as rid
INTO #mytable
FROM othertable

select top 10 * from #mytable order by rid

I've tried every variation of this, but it seems that sybase server iq always returns the same rand() value when I do it like the above. When I try to do

SELECT * FROM othertable order by newid()

I get an error saying it's illegal to use newid() in the order by.

Any suggestions?

like image 566
user1167650 Avatar asked Mar 29 '26 22:03

user1167650


1 Answers

In Sybase T-SQL, The NEWID() system function generates human-readable, globally unique IDs. Include the NEWID() system function in the ORDER BY clause when issuing the SELECT statement on the target table.

Usage:

SELECT top 10 id from TABLE order by NEWID();
like image 189
user1126070 Avatar answered Apr 02 '26 12:04

user1126070



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!