MySQL ORDER BY

The ORDER BY clause is used to sort the result set of a query by one or more columns. You can sort the data in ascending (ASC) or descending (DESC) order. By default, data is sorted in ascending order.

Examples with Tamil Kings

1. Sorting by a Single Column in Ascending Order

SELECT * FROM tamil_kings_auto_increment
ORDER BY king_name ASC;

Code Explanation: This query sorts the result set of the tamil_kings_auto_increment table by the king_name column in ascending order.

2. Sorting by a Single Column in Descending Order

SELECT * FROM tamil_kings_auto_increment
ORDER BY reign_period DESC;

Code Explanation: This query sorts the result set by the reign_period column in descending order.

3. Sorting by Multiple Columns

SELECT * FROM tamil_kings_auto_increment
ORDER BY reign_period DESC, king_name ASC;

Code Explanation: This query sorts the result set by the reign_period column in descending order and then by king_name in ascending order.

Best Practices

  • Use ORDER BY with indexes for large datasets to optimize performance.
  • Always specify the sort order (ASC or DESC) explicitly for clarity.

Key Takeaways

  • The ORDER BY clause sorts the result set in ascending or descending order.
  • You can sort by one or multiple columns.