Skip to content
Quantoros

What does ORDER BY do, and what is the default sort order?

SQLLevel: FoundationFundamentals (Easy)

What does ORDER BY do, and what is the default sort order?

Hints
  • Define one output row and the source-table keys.
  • Check duplicates, NULLs and the order of filtering and aggregation.

Answer

ORDER BY sorts the result set. The default is ASC (ascending). You can specify DESC for descending.

SELECT name, salary
FROM employees
ORDER BY salary DESC, name ASC;

A common interview follow-up: "Where does NULL sort?" In PostgreSQL, NULLs sort last for ASC and first for DESC by default. You can control this with NULLS FIRST / NULLS LAST.

-- PostgreSQL: explicit NULL ordering
SELECT name, last_login
FROM users
ORDER BY last_login DESC NULLS LAST;

Source and licence: SQL Interview Questions — Arda Kocadoru · MIT

Related questions