ORDER BY in MySQL

MySQL ORDER BY In MySQL, the ORDER BY clause is used with the SELECT statement to re-arrange the records of the result set in ascending or descending order.

Syntax:
SELECT expressions  
FROM table_name
WHERE conditions;   
ORDER BY expression [ ASC | DESC ];
Parameters:

expressions: It is used to specify the columns to be retrieved. table_name: It is used to specify the name of the table to retrieve the records. conditions: It is used to specify the conditions to be strictly followed for selection. ASC: It is used to specify the sorting in ascending order, and is an optional parameter. DESC: It is used to specify the sorting in descending order, and is also an optional parameter.

Example: Selecting specific fields from a table in default order. Items table:
ID NAME QUANTITY
1 Electronics 30
2 Sports 45
3 Fashion 100
4 Grocery 90
5 Toys 50

 

Query:

SELECT *
FROM items  
WHERE  quantity >= 50  
ORDER BY quantity;

Output:

QUANTITY
50
90
100

Explanation:

The ‘items’ is an already existing table from which we are selecting rows where the value of the ‘quantity’ column is greater than or equal to 50. The ORDER BY clause is then sorted by the ‘quantity’ column in ascending order by default.

Example: Selecting specific fields from a table in ascending order. Items table:
ID NAME QUANTITY
1 Electronics 30
2 Sports 45
3 Fashion 100
4 Grocery 90
5 Toys 50

 

Query:

SELECT *
FROM items
WHERE quantity >= 50
ORDER BY quantity ASC;

Output:

QUANTITY
50
90
100

Explanation: The ‘items’ is an already existing table from which we are selecting rows where the value of the ‘quantity’ column is greater than or equal to 50. The ORDER BY clause is then sorted by the ‘quantity’ column in ascending order.

Example: Selecting specific fields from a table in descending order. Items table:
ID NAME QUANTITY
1 Electronics 30
2 Sports 45
3 Fashion 100
4 Grocery 90
5 Toys 50

 

Query:

SELECT *
FROM items
WHERE quantity >= 50
ORDER BY quantity DESC;

Output:

QUANTITY
100
90
50

Explanation:

The ‘items’ is an already existing table from which we are selecting rows where the value of the ‘quantity’ column is greater than or equal to 50. The ORDER BY clause is then sorted by the ‘quantity’ column in descending order.

Please follow and like us:
Content Protection by DMCA.com