Back to SQL Notes
Topic #89

SQL ORDER BY Clause

ORDER BY sorts the result set — ascending by default, descending with DESC.

Syntax

SELECT columns
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];

Sample Table: employees

namedepartmentsalary
AmanEngineering65000
RiyaMarketing52000
KaranEngineering71000

Example

SELECT name, salary FROM employees
ORDER BY salary DESC;

Output:

namesalary
Karan71000
Aman65000
Riya52000

Sorting by Multiple Columns

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

Rows are sorted by department first; within each department, by salary highest-to-lowest. The second column only breaks ties within the first.

Sorting by Column Position (Use Sparingly)

SELECT name, salary FROM employees
ORDER BY 2 DESC;   -- sorts by the 2nd selected column (salary)

Works, but is fragile — if the column order in SELECT changes, the sort silently changes too. Naming the column is safer.

Practical Use Case

Leaderboards, "most recent first" feeds, top-N reports — almost any user-facing list needs a defined, intentional order.

Common Mistakes

  • Assuming rows come back in a "natural" or insertion order without ORDER BY — relational databases make no guarantee about row order unless you explicitly sort
  • Sorting by an alias defined in SELECT and expecting it to work in every database the same way — most do support it, but it's technically because ORDER BY executes after SELECT in logical order

Interview Relevance

Q: "If I don't use ORDER BY, what order will my rows come back in?" Correct answer: undefined / implementation-dependent — never rely on it.

Practice Question

Write a query that lists employees sorted by department (A–Z), and within each department, by name (A–Z).

Want to go beyond the notes?

Join Coding Now Tech Institute's SQL course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

SQL ORDER BY Clause – FAQs

Quick answers about learning SQL ORDER BY Clause in SQL.

This free note from Coding Now Tech Institute explains SQL ORDER BY Clause in SQL — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every SQL topic on Coding Now Tech Institute, including SQL ORDER BY Clause, is 100% free with no signup required.
With focused practice, most students grasp SQL ORDER BY Clause in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now