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:
- TypeORM: Find Records by Relation Columns
- Cascade Delete in TypeORM
- TypeORM: How to Execute Raw SQL Queries
- TypeORM: Get Raw SQL Query from QueryBuilder
- TypeORM: ORDER BY Multiple Columns
- Aggregation Operations in TypeORM (Sum, Avg, Min, Max, Count)
You can also check out our database topic page for the latest tutorials and examples.