MySQL: ORDER BY Clause

Profile picture for user arilio666

ORDER BY clause in MySQL is another key feature when it comes to ordering the table content in descending or in ascending order where you wanna know pieces of information about the table in a certain order.

  • So this clause will help do that with ease.
  • We will generally use this clause to get an order of certain columns to our liking.

Syntax

SELECT * from TableName ORDER BY ColumnName;

By default, it will display in the order of ascending order whereas when we want in descending order we will be using the DESC clause to query the table in descending order.

  • For demo purposes, we will be using the order-items table to query out the order quantity and unit price.
  • Basically, we want the total price of the order so we will be doing order quantity multiplied by the unit price we get the total price.
  • So we will basically get the total price of order id 2 alone.
  • This is the example we will be doing today, so let us dive into the scenario.

Here is the order_items table.

Example

select *, quantity * unit_price AS TOTAL from order_items WHERE order_id = 2 ORDER BY TOTAL DESC;

So from the query I have multiplied the quantity column with a unit price to get the total value and named it TOTAL as an alias from the order_items table and as we need total for order id 2 alone so we used the WHERE clause to get 2 with = operator and display TOTAL the name of our alias by descending order using ORDER BY.

Tags