Ira SQL ProIra SQL Pro

ORDER BY Multiple Columns

beginnerfiltering
2 min read

What is ORDER BY with Multiple Columns?

You can sort query results by more than one column. PostgreSQL first sorts by the first column, then by the second column for rows with equal first-column values, and so on.

Syntax

SELECT * FROM table_name
ORDER BY column1 ASC, column2 DESC;

When to Use

  • Sorting employees by department then by name
  • Ordering products by category then by price
  • Creating meaningful sorted reports

Key Points

  1. Priority — Columns listed first have higher sort priority.
  2. Mixed Directions — Each column can independently be ASC or DESC.
  3. Default ASC — If you omit the direction, ASC is the default.
  4. Column Position — You can use column numbers: ORDER BY 1, 2 DESC (but naming is clearer).
  5. NULLs — Each column can have its own NULLS FIRST/LAST setting.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

ORDER BY Multiple Columns Challenge

Write a query that solve this task: order students by grade ascending, then alphabetically by last name.

Expected result

Students sorted by grade, and within each grade by last name alphabetically.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What is ORDER BY with Multiple Columns?

Initializing database...Each run starts from fresh sample data.

More Examples

Mixed sort directions

Show products by category ascending and price descending.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

How many columns can I use in ORDER BY?
There is no practical limit. You can sort by as many columns as exist in your result set.
Can I mix ASC and DESC in the same ORDER BY?
Yes. Each column in ORDER BY can have its own direction: ORDER BY col1 ASC, col2 DESC.

Related Topics