# sortBy

> For the complete documentation index, see [llms.txt](https://kotlin.github.io/dataframe/llms.txt).

Returns [DataFrame](dataframe.html) with rows sorted by one or several columns.

API reference: [sortBy](https://kotlin.github.io/dataframe/api-docs/core/org.jetbrains.kotlinx.dataframe.api/sort-by.html)

By default, columns are sorted in ascending order with `null` values going first. Available modifiers:

* `.desc` — changes column sort order from ascending to descending

* `.nullsLast` — forces `null` values to be placed at the end of the order

Related operations: [Reorder rows](reorderrows.html)

See [column selectors](columnselectors.html) for how to select the columns for this operation.

Properties:

```KOTLIN
df.sortBy { age }
df.sortBy { age and name.firstName.desc() }
df.sortBy { weight.nullsLast() }
```

Strings:

```KOTLIN
df.sortBy("age")
df.sortBy { "age" and "name"["firstName"].desc() }
df.sortBy { "weight".nullsLast() }
```

[Embedded content](resources/org.jetbrains.kotlinx.dataframe.samples.api.Modify.sortBy.html)

## sortByDesc

Returns [DataFrame](dataframe.html) sorted by one or several columns in descending order.

See [column selectors](columnselectors.html) for how to select the columns for this operation.

Properties:

```KOTLIN
df.sortByDesc { age and weight }
```

Strings:

```KOTLIN
df.sortByDesc("age", "weight")
```

[Embedded content](resources/org.jetbrains.kotlinx.dataframe.samples.api.Modify.sortByDesc.html)

## Sorting within groups

On a [GroupBy](groupby.html), `sortBy` and `sortByDesc` sort rows only within each group.

If a referenced column cannot be found in a group, both functions throw an exception.

To sort the groups themselves by their keys, use `sortByKey()` or `sortByKeyDesc()` instead. See [GroupBy transformations](groupby.html#transformation) for other operations that reorder groups.

## sortWith

Returns [DataFrame](dataframe.html) sorted with comparator.

```KOTLIN
df.sortWith { row1, row2 ->
    when {
        row1.age < row2.age -> -1
        row1.age > row2.age -> 1
        else -> row1.name.firstName.compareTo(row2.name.firstName)
    }
}
```

[Embedded content](resources/org.jetbrains.kotlinx.dataframe.samples.api.Modify.sortWith.html)

If called on a [DataColumn](datacolumn.html), `sortWith()` returns the sorted version of the current column based on the given comparator.

