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

SELECT column FROM table
ORDER BY RAND()
LIMIT 1
Copy after login

PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
Copy after login

Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()
Copy after login

IBM DB2:

SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
Copy after login

Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1
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!

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