Home >Database >Mysql Tutorial >How to Select a Random Row from a SQL Database?

How to Select a Random Row from a SQL Database?

Susan Sarandon
Susan SarandonOriginal
2025-01-23 06:12:09491browse

How to Select a Random Row from a SQL Database?

Selecting Random Records in SQL Databases

Database queries often target specific rows. But how do you efficiently retrieve a completely random row? The methods vary slightly across different database systems:

MySQL:

<code class="language-sql">SELECT column FROM table
ORDER BY RAND()
LIMIT 1</code>

PostgreSQL:

<code class="language-sql">SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1</code>

Microsoft SQL Server:

<code class="language-sql">SELECT TOP 1 column FROM table
ORDER BY NEWID()</code>

IBM DB2:

<code class="language-sql">SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY</code>

Oracle:

<code class="language-sql">SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1</code>

These examples demonstrate how to obtain a single random row. Remember to replace column and table with your actual column and table names.

The above is the detailed content of How to Select a Random Row from a SQL Database?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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