Sort API results in ascending or descending order using the NestJS CRUD framework
Sorting allows you to order API results by one or more fields in ascending or descending order. This is essential for presenting data in a meaningful way to users.
Ascending sort orders results from lowest to highest:
# Sort users by name (A to Z)GET /users?sort=name,ASC# Sort products by price (lowest to highest)GET /products?sort=price,ASC# Sort posts by date (oldest first)GET /posts?sort=createdAt,ASC
Descending sort orders results from highest to lowest:
# Sort users by name (Z to A)GET /users?sort=name,DESC# Sort products by price (highest to lowest)GET /products?sort=price,DESC# Sort posts by date (newest first)GET /posts?sort=createdAt,DESC
You can sort by multiple fields by adding multiple sort parameters:
# Sort by status (ASC), then by name (ASC)GET /users?sort=status,ASC&sort=name,ASC# Sort by priority (DESC), then by createdAt (DESC)GET /tasks?sort=priority,DESC&sort=createdAt,DESC
The order of sort parameters matters:
First sort parameter is the primary sort
Second sort parameter is applied when primary values are equal
# Oldest firstGET /posts?sort=createdAt,ASC# Newest first (most common)GET /posts?sort=createdAt,DESC# Sort by last updateGET /articles?sort=updatedAt,DESC
# Get active users sorted by nameGET /users?filter=isActive||eq||true&sort=name,ASC# Get products under $100 sorted by priceGET /products?filter=price||lt||100&sort=price,ASC
# Get first 10 users sorted by creation dateGET /users?sort=createdAt,DESC&limit=10&page=1# Get next 10 usersGET /users?sort=createdAt,DESC&limit=10&page=2
Always use the same sort order across paginated requests to ensure consistent results.
For optimal performance, create database indexes on frequently sorted fields:
// TypeORM example@Entity()@Index(['createdAt']) // Index for sorting by creation dateexport class Post { @PrimaryGeneratedColumn() id: number; @Column() title: string; @CreateDateColumn() createdAt: Date;}
# Show newest users firstGET /users?sort=createdAt,DESC&limit=50# Show users alphabeticallyGET /users?sort=lastName,ASC&sort=firstName,ASC# Show most active usersGET /users?sort=loginCount,DESC&filter=isActive||eq||true
# Price: Low to HighGET /products?filter=category||eq||electronics&sort=price,ASC# Price: High to LowGET /products?filter=category||eq||electronics&sort=price,DESC# Most PopularGET /products?sort=salesCount,DESC&limit=10# Newest ArrivalsGET /products?sort=createdAt,DESC&limit=20
# Latest postsGET /posts?filter=status||eq||published&sort=publishedAt,DESC# Most commented postsGET /posts?sort=commentsCount,DESC&limit=10# Posts by category, then dateGET /posts?sort=category,ASC&sort=publishedAt,DESC
# High priority tasks first, then by due dateGET /tasks?filter=status||eq||pending&sort=priority,DESC&sort=dueDate,ASC# Recently updated tasksGET /tasks?sort=updatedAt,DESC# Overdue tasks firstGET /tasks?filter=dueDate||lt||2024-01-01&sort=dueDate,ASC