When processing large data sets, it may be necessary to randomly select a subset of rows for processing or analysis. SQL provides several ways to accomplish this task.
A common way to randomly select rows in Microsoft SQL Server is to use the NEWID() function. The following query retrieves 5 random rows of data from the customerNames table:
<code class="language-sql">SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID()</code>
The NEWID() function generates a globally unique identifier (GUID) that changes each time the query is executed, ensuring a different set of rows is returned each time.
Other SQL implementations use different syntax to randomly select rows. The following table provides examples of commonly used databases:
数据库 | 语法 |
---|---|
MySQL | ORDER BY RAND() |
PostgreSQL | ORDER BY RANDOM() |
Oracle | ORDER BY dbms_random.value |
SQLite | ORDER BY RANDOM() |
IBM DB2 | ORDER BY RAND() |
The above is the detailed content of How Can I Randomly Select Rows in SQL?. For more information, please follow other related articles on the PHP Chinese website!