Home > Database > Mysql Tutorial > How Can I Randomly Select Rows in SQL?

How Can I Randomly Select Rows in SQL?

Barbara Streisand
Release: 2025-01-17 12:51:13
Original
277 people have browsed it

How Can I Randomly Select Rows in SQL?

SQL random row selection

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.

Microsoft SQL Server

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>
Copy after login

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

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template