MySQL ORDER BY Clause

MySQL ORDER BY Clause

The MYSQL ORDER BY Clause is used to sort the records in ascending or descending order.

Syntax:

  1. SELECT expressions
  2. FROM tables
  3. [WHERE conditions]
  4. ORDER BY expression [ ASC | DESC ];

Parameters

expressions: It specifies the columns that you want to retrieve.

tables: It specifies the tables, from where you want to retrieve records. There must be at least one table listed in the FROM clause.

WHERE conditions: It is optional. It specifies conditions that must be fulfilled for the records to be selected.

ASC: It is optional. It sorts the result set in ascending order by expression (default, if no modifier is provider).

DESC: It is also optional. It sorts the result set in descending order by expression.

MySQL ORDER BY: without using ASC/DESC attribute

If you use MySQL ORDER BY clause without specifying the ASC and DESC modifier then by default you will get the result in ascending order.

Execute the following query:

  1. SELECT *
  2. FROM officers
  3. WHERE address = ‘Lucknow’
  4. ORDER BY officer_name;

Output:

or

MySQL ORDER BY: with ASC attribute

Let’s take an example to retrieve the data in ascending order.

Execute the following query:

  1. SELECT *
  2. FROM officers
  3. WHERE address = ‘Lucknow’
  4. ORDER BY officer_name ASC;

Output:

or1

MySQL ORDER BY: with DESC attribute

  1. SELECT *
  2. FROM officers
  3. WHERE address = ‘Lucknow’
  4. ORDER BY officer_name DESC;

or2

MySQL ORDER BY: using both ASC and DESC attributes

Execute the following query:

  1. SELECT officer_name, address
  2. FROM officers
  3. WHERE officer_id < 5
  4. ORDER BY officer_name DESC, address ASC;

Output:

or0