-1

Here is the code I used

SELECT * FROM   
(SELECT * FROM [table name] 
ORDER BY dbms_random.value)
WHERE rownum < 10

I would like to select random rows only from records with column A = XYZ. I tried to add a WHERE clause in the code:

SELECT * FROM   
(SELECT * FROM [table name] 
WHERE [column A] = 'XYZ'
ORDER BY dbms_random.value)
WHERE rownum < 10

but got an error. Any feedback would be greatly appreciated.

Nick
  • 138,499
  • 22
  • 57
  • 95

2 Answers2

2

You can try the below approach in SQL Server:

SELECT TOP 10 * FROM [table name] 
WHERE [column A] = 'XYZ'
ORDER BY newid()

More information on how ORDER BY newid() works in a SO post

Venkataraman R
  • 12,181
  • 2
  • 31
  • 58
0

Your code looks like Oracle code. It does not recognize square braces for identifiers. In fact, don't escape them -- or use double quotes if you must:

SELECT t.*   
FROM (SELECT t.*
      FROM t 
      WHERE columnA = 'XYZ'
      ORDER BY dbms_random.value
     ) t
WHERE rownum < 10;

In SQL Server, the equivalent would be:

SELECT TOP (10) t.*
FROM t 
WHERE columnA = 'XYZ'
ORDER BY NEWID()
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • @MitchWheat . . . The OP claims that s/he used the first query, presumably with no error. That strongly suggests that the OP is not using SQL Server. – Gordon Linoff Mar 22 '20 at 14:38