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' })
@Unique(['email'])
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}

Get a random user:

const userRepository = myDataSource.getRepository(User);
const randomUser = await userRepository
      .createQueryBuilder('user')
      .select()
      .orderBy('RANDOM()')
      .getOne();

console.log(randomUser);

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
      .createQueryBuilder('user')
      .select()
      .orderBy('RANDOM()')
      .take(10)
      .getMany();

console.log(randomUsers);

That’s it. Further reading:

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles