Sorting query results Which SQL clause is used to sort the rows returned by a query in ascending or descending order by one or more expressions?

Difficulty: Easy

Correct Answer: ORDER BY

Explanation:


Introduction / Context:
Result ordering is different from grouping or filtering. SQL separates these concerns so that you can control the presentation of rows without changing which rows qualify or how aggregates are computed.



Given Data / Assumptions:

  • We already have a SELECT statement that returns rows.
  • We want to specify the order of those rows.
  • Ordering may use column positions, names, or expressions.


Concept / Approach:

ORDER BY instructs the DBMS to sort the final result set. You can specify ASC or DESC for each sort key. GROUP BY forms groups for aggregation and does not imply any particular output order unless ORDER BY is also used. Non-standard clauses like SORT BY or ALIGN BY are not part of ANSI SQL (though some systems may offer syntactic sugar).



Step-by-Step Solution:

Add ORDER BY to the end of the SELECT statement.Provide one or more expressions: ORDER BY last_name ASC, first_name ASC.Use DESC for descending when needed: ORDER BY order_date DESC.Be aware of NULLS FIRST/NULLS LAST behavior depending on DBMS.


Verification / Alternative check:

ANSI SQL grammar places ORDER BY after SELECT ... FROM ... WHERE ... GROUP BY ... HAVING.



Why Other Options Are Wrong:

  • SORT BY / ALIGN BY / RANK BY: not ANSI-standard sort clauses.
  • GROUP BY: used for aggregation, not sorting.


Common Pitfalls:

  • Relying on implicit order; without ORDER BY, the row order is not guaranteed.
  • Sorting large datasets without proper indexes can be expensive; consider adding indexes on sort keys for frequent sorts.


Final Answer:

ORDER BY

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion