SORT in SQL

SORT puts rows in order by one or more columns; in SQL you add an ORDER BY clause to the query.

The Excel version

=SORT(A2:C100, 3, -1)

The SQL equivalent

This example assumes: sales(id bigint, region text, amount numeric, sale_date date). It is written in PostgreSQL syntax, and your table and column names will differ from these.

SELECT id, region, amount, sale_date
FROM sales
ORDER BY amount DESC, sale_date DESC
LIMIT 20;

How it works

  • ORDER BY amount DESC sorts from largest to smallest, like sort order -1 in SORT.
  • A second column breaks ties, as with a multi-level sort in Excel.
  • LIMIT 20 keeps the top twenty rows, the same as taking the first twenty rows of a sorted range.

Where the results differ from Excel

  • A SQL table has no inherent order: without ORDER BY the rows can come back in any order.
  • Nulls sort last in ascending order and first in descending order in PostgreSQL; Excel places blanks at the end either way.
  • Text sorting in SQL depends on the database collation, so capital and accented letters may order differently from Excel.

Skip the query: ask in plain English

If you would rather not write SQL, type the question. SchemaChat turns it into SQL against your connected database or uploaded file, runs it, and shows the SQL and the figures it used so you can check the answer before you share it. Check that the result matches how your spreadsheet defines the number.

  • Show the 20 biggest sales.
  • List sales by date, newest first.

Frequently asked questions

What is the SQL equivalent of SORT?
SORT puts rows in order by one or more columns; in SQL you add an ORDER BY clause to the query.
How does the SQL version of SORT work?
ORDER BY amount DESC sorts from largest to smallest, like sort order -1 in SORT. A second column breaks ties, as with a multi-level sort in Excel. LIMIT 20 keeps the top twenty rows, the same as taking the first twenty rows of a sorted range.
Why can SQL give a different result from SORT?
A SQL table has no inherent order: without ORDER BY the rows can come back in any order.