Order By

Dictating in what order your results come back to you helps you stay organized with your data. Using the ORDER BY statement in your SQL query can accomplish that.

Order by

When you want to run a simple ORDER BY on a particular column then you can simply provide the string value of the column name you desire.

const { data, error } = db
    .selectFrom([
        { table: 'table_name', columns: ['first_name'] }
    ])
    .orderBy('first_name') // Orders it by the first_name column
    .query()

Ascending order

To order a column in ascending order, rather than just supplying the name of the column to order by you can declare it to be in ascending order by using the helper function shown below.

const { data, error } = db
    .selectFrom([
        { table: 'table_name', columns: ['first_name'] }
    ])
    .orderBy(ascending('first_name')) // Returns from A-Z
    .query()

Descending order

Similarly to using the helper function above for ascending, to order a column in descending order, you can use the function to declare it to be in descending order

const { data, error } = db
    .selectFrom([
        { table: 'table_name', columns: ['first_name'] }
    ])
    .orderBy(descending('first_name')) // Returns from Z-A
    .query()

Last updated