SQL >> Base de Datos >  >> RDS >> Sqlserver

Elegir filas aleatorias de una tabla SQL Server

La forma clásica de obtener una muestra aleatoria es ordenar por un GUID aleatorio:

select top 10 percent *
from [yourtable]
order by newid()

En tablas muy grandes esto puede ser costoso. Una variante más eficiente restringe el orden aleatorio primero a la columna clave:

select *
from [yourtable]
where [yourPk] in (
 select top 10 percent [yourPk]
 from [yourtable]
 order by newid()
)