Sort

Orders rows based on the values of one or more columns.

1. sort [{direction}{column}]

Parameters

  • One column or a list of columns to sort by
  • Each column can be prefixed with:
  • +, for ascending order, the default
  • -, for descending order
  • When using prefixes, even a single column needs to be in a list or parentheses. (Otherwise, sort -foo is parsed as a subtraction between sort and foo.)

Examples

PRQL

1. from employees
2. sort age

SQL

1. SELECT
2. *
3. FROM
4. employees
5. ORDER BY
6. age

PRQL

1. from employees
2. sort [-age]

SQL

1. SELECT
2. *
3. FROM
4. employees
5. ORDER BY
6. age DESC

PRQL

1. from employees
2. sort [age, -tenure, +salary]

SQL

1. SELECT
2. *
3. FROM
4. employees
5. ORDER BY
6. age,
7. tenure DESC,
8. salary

We can also use expressions:

PRQL

1. from employees
2. sort [s"substr({first_name}, 2, 5)"]

SQL

1. WITH table_1 AS (
2. SELECT
3. *,
4. substr(first_name, 2, 5) AS _expr_0
5. FROM
6. employees
7. ORDER BY
8. _expr_0
9. )
10. SELECT
11. *
12. FROM
13. table_1 AS table_0

Notes

Ordering guarantees

Most DBs will persist ordering through most transforms; for example, you can expect this result to be ordered by tenure.

PRQL

1. from employees
2. sort tenure
3. derive name = f"{first_name} {last_name}"

SQL

1. SELECT
2. *,
3. CONCAT(first_name, ' ', last_name) AS name
4. FROM
5. employees
6. ORDER BY
7. tenure

But:

  • This is an implementation detail of the DB. If there are instances where this doesn’t hold, please open an issue, and we’ll consider how to manage it.
  • Some transforms which change the existence of rows, such as join or group, won’t persist ordering; for example:

PRQL

1. from employees
2. sort tenure
3. join locations [==employee_id]

SQL

1. WITH table_1 AS (
2. SELECT
3. *
4. FROM
5. employees
6. ORDER BY
7. tenure
8. )
9. SELECT
10. table_0.*,
11. locations.*
12. FROM
13. table_1 AS table_0
14. JOIN locations ON table_0.employee_id = locations.employee_id

See Issue #1363 for more details.