In TypeORM, you can order your results by multiple columns. The 2 examples below show you how to do that. The first example uses the find() method whilst the second one uses a query builder. In both of these examples, we will work with an entity named Product:
// KindaCode.com
// Product entity
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ default: 0 })
price: number;
@Column({ default: 0 })
shippingFee: number;
@Column({ default: new Date() })
yearOfManufacture: Date;
}
Using find() method
This sorts our products by price (ascending) first, then by shippingFee (ascending), and then by yearOfManufacture (descending). It’s important to know that sorting by shipping fee will only happen between products of the same price. Sorting by year of manufacture will only occur between products with the same price and shipping charges.
const productRepository = myDataSource.getRepository(Product);
const products = await productRepository.find({
where: {
/* conditons, if any */
},
// sort by multiple columns
order: {
price: 'ASC',
shippingFee: 'ASC',
yearOfManufacture: 'DESC',
},
});
console.log(products);
Using Query Builder
This code snippet below does the same thing as the first example, but in a different manner:
const productRepository = myDataSource.getRepository(Product);
const products = await productRepository
.createQueryBuilder('product')
.select()
.orderBy('product.price', 'ASC')
.addOrderBy('product.shippingFee', 'ASC')
.addOrderBy('product.yearOfManufacture', 'DESC')
.getMany();
console.log(products);
For each additional sort criterion, you have to add an addOrderBy in the query builder chain.
That’s it. Further reading:
- How to Use Subqueries in TypeORM
- TypeORM: Get Raw SQL Query from QueryBuilder
- TypeORM: How to Use Column Alias when Querying Data
- TypeORM: Selecting DISTINCT Values
- TypeORM Upsert: Update If Exists, Create If Not Exists
You can also check out our database topic page for the latest tutorials and examples.