Fetch Random rows from Database (MySQL, Oracle, MS SQL, PostgreSQL)

Ever thought why would one need to fetch random rows from a database table? You may want to display some random information (like articles/pages/links) to your user. I had a requirement wherein I had to fetch 10 random rows from MySQL database and display it on screen. I used following simple query for retrieving random records from database table. Also note that there are number of ways one can fetch random rows from table. Easiest way is to use sql queries to do so. Now there are some different queries depending on your database server. Following are the examples of fetching random rows in some popular databases.

Select random rows in MySQL

Following query will fetch 10 random rows from MySQL.
SELECT column FROM table ORDER BY RAND() LIMIT 10
Code language: SQL (Structured Query Language) (sql)

Select random rows in Oracle

SELECT column FROM ( SELECT column FROM table ORDER BY dbms_random.value ) WHERE rownum <= 10 [/code] <h2>Select random rows in PostgreSQL</h2> <!-- wp:code {"language": "sql"} --><pre class="wp-block-code"><code></code></pre><!-- /wp:code --> SELECT column FROM table ORDER BY RANDOM() LIMIT 10
Code language: SQL (Structured Query Language) (sql)

Select random rows in Microsoft SQL Server

SELECT TOP 10 column FROM table ORDER BY NEWID()
Code language: SQL (Structured Query Language) (sql)
Also, do comment if you have some variant of the queries described in above article.

View Comments

Share
Published by
Viral Patel
Tags: Database database queries mssql MySQL Oracle postgresql SQL

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago