Skip to main content
orderBy is a method for sorting query results by specific columns. You can sort in ascending (ASC) or descending (DESC) order, and can sort by multiple columns.

Basic Usage

Ascending (ASC)

Descending (DESC)

Multiple Column Sorting

You can sort by multiple columns by chaining orderBy.
Sort Priority:
  1. First orderBy - Primary sort
  2. Second orderBy - Secondary sort (when primary is same)
  3. Third orderBy - Tertiary sort (when secondary is also same)

NULL Sort Order (nulls)

The third argument nulls specifies where NULL values should be placed in the sort order.
nulls options:

Array-style orderBy

You can pass multiple sort conditions as an array in a single call.
Each array item can be one of the following:
  • string: Column name only (defaults to ASC)
  • SqlExpression: SQL expression
  • object: { column, order?, nulls? } for detailed specification

Practical Examples

Sorting Joined Tables

You can also sort by columns from joined tables.

Sorting by SELECT Alias

You can also sort by aliases specified in SELECT.

Sorting Aggregate Functions

You can sort by aggregate function results with GROUP BY.

Sorting by SQL Expressions

orderBy accepts SqlExpression<"number"> or SqlExpression<"string"> instead of a column name. This is useful when sorting by computed values such as full-text search rankings or similarity scores.

Sorting by Search Rank

Sorting by Similarity Score

Custom Sorting with rawNumber

When using SQL expressions, orderByRaw is used internally and parameter bindings are automatically applied.

Sort Directions

ASC (Ascending)

  • Numbers: small → large
  • Strings: A → Z
  • Dates: past → future
  • NULL: last

DESC (Descending)

  • Numbers: large → small
  • Strings: Z → A
  • Dates: future → past
  • NULL: last
Default is ASC. If direction is not specified, it sorts in ascending order.

Performance Optimization

1. Use Indexes

Recommended Indexes:

2. Use with LIMIT

3. Composite Indexes

When sorting by multiple columns, composite indexes are needed.

Cautions

1. Sort Order Matters

2. NULL Values

3. Case Sensitivity

4. Performance Impact

Type Safety

orderBy validates columns in a type-safe manner.

Next Steps

limit

Limit result count

where

Filter with conditions

select

Select fields to query

join

Join tables