ORDER BY
The clause that sorts a query's answer by one or more columns, each ascending or descending.
In more detail
A table has no order of its own, so without ORDER BY any order is a correct answer and may change when data or indexes change. With several sort keys, later keys break ties in earlier ones. Sorting happens last, after filtering and grouping.
Examples
ORDER BY team, salary DESCIn this course: Without ORDER BY a database may return rows in any order and change that order between runs, so a test must never rely on row order it did not ask for. Asserting on an unordered result is a common cause of flaky database tests.Related terms
- ASC and DESC — The sort directions in ORDER BY: ASC for smallest first, the default, and DESC for largest first.
- NULLS FIRST and NULLS LAST — ORDER BY options that say whether NULL values sort before or after all other values.
- LIMIT — A clause that returns at most a given number of rows, optionally after skipping a number of rows with OFFSET.
- pagination — Splitting a large collection into bounded pages, each with a way to ask for the next one.
- SQL — The standard language for defining, querying and changing data in a relational database.
- flaky test — A test that sometimes passes and sometimes fails on the same code, because it depends on something it does not control.
Taught in
- Thirty Eight Percent More: Billing Models And Tags — CompTIA Cloud+ (CV0-004) Exam Prep
- Ordering And Limiting Results — PostgreSQL, Indexing & Relational Data Modeling
- The GROUP BY Clause — PostgreSQL, Indexing & Relational Data Modeling
- Testing With Real Databases — Automated Testing, TDD & Quality Engineering