Sorting Tables

Written by

Soumya Shaw


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

Okay, now let us assume that the Government now needs a list of States in the Descending Order of its Population. So, let us look at the way we can help our Government.

SELECT state, capital, population
FROM country
ORDER BY population DESC;

Note: The table is arranged in Ascending Order by Default. So, even you forget to mention the order being Ascending, MySQL will do it for you. You may have noticed that the tables are arranged by the Ascending Order of the Primary Key and if the mentioned order precedence is same then arrangement will follow the order of Primary Key.

SELECT train_name, source_stn, destination_stn, costperkm
FROM railways
ORDER BY costperkm;

You can very well see the Ascending nature of the Output and where the values are same in the Requested column, where the order is decided by Primary Key (Train_No).

But, the ORDER BY Clause is not only limited by Numbers. It can also be operated on Dates as well as Strings!

SELECT name, product, price, mfd
FROM store
WHERE damage LIKE "%No%"

This example involves a Mixture of many Clauses and is a typical use of the Queries. You can observe that the List is Ordered by the MFD and only which are ‘Not Damaged’.

FROM air_force
ORDER BY ranks;

The Details are arranged in the Order of their Ranks alphabetically.

Sorting Tables