Kinda Code
Home/Flutter/TypeORM: How to Select Random Rows

TypeORM: How to Select Random Rows

Last updated: September 27, 2022

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.