sqlsql-server-2008selectrandomnewid

Select random rows from table


I want to select 24 Random rows from whole table of Admin_Pic_Lib, but this Query give syntax error,

 SELECT top 24 CAST( [Pictures] AS varbinary(Max)) FROM Admin_Pic_Lib ORDER BY NEWID()

 UNION ALL 

  SELECT  CAST([Pictures] AS varbinary(Max))   FROM User_images  WHERE UserName ='ahmed'

When I am trimming ORDER BY NEWID() it only select top 24 rows.


Solution

  • Please try the below code.

    SELECT Pictures 
    FROM 
        (SELECT TOP 24 CAST([Pictures] AS varbinary(Max)) AS Pictures 
         FROM Admin_Pic_Lib ORDER BY NEWID()) AS X
    
     UNION ALL 
    
      SELECT  CAST([Pictures] AS varbinary(Max)) AS Pictures 
      FROM User_images
      WHERE UserName ='ahmed'