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
Release: 2025-01-23 06:12:09
Original
465 people have browsed it

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

PostgreSQL:

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

Microsoft SQL Server:

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

IBM DB2:

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

Oracle:

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

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!

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