MySQL ORDER BY Keyword

MySQL Tutorial

 MySQL ORDER BY Keyword 

The ORDER BY keyword in MySQL is used to sort the result set of a query in ascending or descending order.

 It is widely used in reports, rankings, pagination, and interviews.


 What is ORDER BY?

  • Sorts rows based on one or more columns

  • Default sorting is ascending

  • Affects only the result, not stored data

 Sorting can be done on numbers, strings, and dates.


 Basic Syntax


 ORDER BY ASC (Ascending – Default)

  •  Lowest marks first
  • ASC is optional

 ORDERS BY DESC (Descending)

  •  Highest salary first
  •  Very common in Top-N queries

 ORDER-BY Multiple Columns

  •  First sorts by department,
  • then sorts salary inside each department

 ORDER-BY with Column Position

  • Sorts by 2nd column (marks)
  • Not recommended (less readable)

ORDER BY with Alias

  •  Alias can be used in ORDER BY

 ORDERS BY with WHERE

  • WHERE filters rows before sorting

 ORDERS BY with GROUP BY

  •  Sorts grouped results

ORDER-BY with LIMIT (Very Important)

  •  Top 5 highest salaries
  •  Very common interview question

ORDERS BY with NULL Values

  • ASC → NULLs come first

  • DESC → NULLs come last


ORDER BY vs GROUP BY (Interview)

FeatureORDER BYGROUP BY
PurposeSortingGrouping
AffectsResult orderAggregation
Aggregate functions NoYes

 Common Mistakes

  •  Expecting ORDER BY to store sorted data
  •  Forgetting ASC/DESC meaning
  • Using column position blindly
  •  Confusing ORDER BY with GROUP BY

Interview Questions & MCQs (Very Important)

Q1. What does ORDER BY do?

A) Groups rows
B) Filters rows
C) Sorts rows
D) Deletes rows

Answer: C


Q2. Default order of ORDER BY?

A) DESC
B) RANDOM
C) ASC
D) NULL

Answer: C


Q3. Can ORDER BY use column alias?

A) Yes
B) No

Answer: A


Q4. Which clause is executed last?

A) WHERE
B) GROUP BY
C) ORDER BY
D) HAVING

Answer: C


Q5. Which query gives top 3 salaries?

SELECT * FROM employees
ORDER BY salary DESC
LIMIT 3;

A) Correct
B) Incorrect

Answer: A


Q6. Can ORDER BY sort by multiple columns?

A) Yes
B) No

Answer: A


Real-Life Use Cases

  •  Ranking students/employees
  •  Leaderboards
  •  Latest records first
  •  Pagination sorting
  •  Reports & dashboards

 Summary

  • ORDER BY sorts query results

  • Default order is ASC

  • Supports multiple columns

  • Works with aliases & LIMIT

  • Essential for ranking & pagination

  • Very important for SQL exams & interviews

You may also like...