Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to SQL Notes
Topic #210

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).

Related SQL Notes

Want to go beyond the notes?

Join CodingNow's SQL course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →