ORDER BY sorts returned relation records by one or more columns or expressions. It appears after grouping and before LIMIT in a SELECT statement, making analytical results easier to inspect and consume. section 3.1 section 3.4.4
Use ORDER BY to:
- Sort grouped results, such as yearly minimum and maximum prices, with ORDER BY year. section 3.4.4
- Create descending top-results views, such as the three highest power readings with ORDER BY power DESC LIMIT 3. section 4.5
- Compose programmatic relation pipelines with the DuckDBPyRelation order method, such as ordering regional population aggregates by pop DESC. section 6.2.2
- Distinguish final-result sorting from ORDER BY inside OVER(), which controls window-function execution order without sorting the query result. section 4.5
Sort and limit power readings
SELECT * FROM readings ORDER BY power DESC LIMIT 3; returns the three readings with the greatest power values, displaying tied rows when they share the maximum. section 4.5
Listing 3.10 The structure of a SELECT statement
SELECT select_list FROM tables WHERE condition GROUP BY groups HAVING group_filter ORDER BY order_expr LIMIT n
Use the SELECT structure to locate ORDER BY after HAVING and before LIMIT when composing a query. section 3.4.4


