TypeORM: How to Select Random Rows

Updated: September 27, 2022 By: Snowball Post a comment

In TypeORM, you can select a single or multiple random rows by adding orderBy(‘RANDOM()’) to your query builder. Let’s see a couple of examples below for more clarity.

Let’s say we have a User entity like this:

// KindaCode.com
// User entity
import { Entity, PrimaryGeneratedColumn, Column, Unique} from 'typeorm';

@Entity({ name: 'users' })
export class User {
  id: number;

  name: string;

  email: string;

Get a random user:

const userRepository = myDataSource.getRepository(User);
const randomUser = await userRepository


Retrieve many random users (replace getOne() with getMany() and specify the number of results you want in the take() method):

const userRepository = myDataSource.getRepository(User);
const randomUsers = await userRepository


That’s it. Further reading:

You can also check out our database topic page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles