Cover Image for MySQL ORDER BY
80 views

MySQL ORDER BY

The MySQL ORDER BY clause is used to sort the result set of a SELECT query based on one or more columns. You can use it to specify the order in which you want the rows to appear in the query result. By default, ORDER BY sorts the rows in ascending order, but you can also sort them in descending order.

The basic syntax of the ORDER BY clause is as follows:

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

Here’s how it works:

  • column1, column2, and so on represent the columns by which you want to sort the result set.
  • table_name is the name of the table from which you are selecting data.
  • ORDER BY specifies the sorting criteria for the rows.
  • You can specify one or more columns by which you want to sort the data.
  • You can use ASC (ascending) or DESC (descending) to control the sorting order. The default is ASC.

Here are some examples of how to use the ORDER BY clause in MySQL:

  1. Sort the result set of a SELECT query in ascending order based on the product_name column:
   SELECT product_name, price
   FROM products
   ORDER BY product_name;
  1. Sort the result set in descending order based on the price column:
   SELECT customer_name, order_date, total_amount
   FROM orders
   ORDER BY total_amount DESC;
  1. Sort the result set by multiple columns. If there is a tie in the first column, it will be sorted by the second column:
   SELECT product_category, product_name, price
   FROM products
   ORDER BY product_category, price;
  1. Sort the result set in ascending order by one column and in descending order by another column:
   SELECT employee_name, hire_date
   FROM employees
   ORDER BY hire_date ASC, employee_name DESC;

The ORDER BY clause is essential for controlling the order in which rows appear in the result set. It is commonly used for presenting data in a meaningful way, such as sorting results by alphabetical order, date, or numerical values. You can sort data based on one or more columns, and you have the flexibility to choose between ascending and descending order for each column.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS