T-SQL SELECT Random Rows in UNION

To Select random rows from a Table, use the ORDER BY NEWID()

SELECT * FROM Table ORDER BY NEWID();

SELECT TOP 10 PERCENT * FROM Table ORDER BY NEWID();

SELECT TOP 10 * FROM Table ORDER BY NEWID();
To Select random rows from a Table UNION Table, then do:

SELECT * FROM (SELECT TOP 10 Column1, Column2, Column 3 FROM Table1 ORDER BY NEWID()) TableA
UNION
SELECT * FROM (SELECT TOP 10 Column1, Column2, Column3 FROM Table2 ORDER BY NEWID()) TableB;

1 comment:

Muzi said...

Awesome!
this is what i was looking for!

very simple and straight to the point!

Thanks