SQL SORTING Results

By | September 13, 2020
SQL SORTING Results

To fetch or display the data in sorted ascending or descending or we use SQL ORDER BY clause. And by default the ORDER BY sorting give support for Ascending order.

SQL SORTING Results

Syntax

Vamware

To use the basic ORDER BY clause follow, this syntax:

SELECT column_name_x .... 
FROM table_name 
WHERE [condition] 
ORDER BY [column1, column2, .. columnN] [ASC | DESC];

Example

For the example consider this table of students:

+------+--------+------+--------+-------+----------+
| id   | name   | age  | grades | marks | Trade    |
+------+--------+------+--------+-------+----------+
|    1 | Luffy  |   16 | A      |   970 | Science  |
|    2 | Naruto |   18 | A      |   960 | Humanity |
|    3 | Zoro   |   20 | A      |   940 | Commerce |
|    4 | Sanji  |   21 | B      |   899 | Humanity |
|    5 | Nami   |   17 | B      |   896 | Science  |
|    6 | Robin  | NULL | B      |   860 | Humanity |
+------+--------+------+--------+-------+----------+

Query: Display the Students records and sort them in ascending order by their names.

SELECT *
FROM students
ORDER BY name;

Output

+------+--------+------+--------+-------+----------+
| id   | name   | age  | grades | marks | Trade    |
+------+--------+------+--------+-------+----------+
|    1 | Luffy  |   16 | A      |   970 | Science  |
|    5 | Nami   |   17 | B      |   896 | Science  |
|    2 | Naruto |   18 | A      |   960 | Humanity |
|    6 | Robin  | NULL | B      |   860 | Humanity |
|    4 | Sanji  |   21 | B      |   899 | Humanity |
|    3 | Zoro   |   20 | A      |   940 | Commerce |
+------+--------+------+--------+-------+----------+

here we did not mention the wildcard ASC or DESC but the SQL show the students record in ascending order according to their names.

Query: Display students names and marks, and sort them in descending order by name.

SELECT name, marks
FROM students
ORDER BY name DESC;

Output

+--------+-------+
| name   | marks |
+--------+-------+
| Zoro   |   940 |
| Sanji  |   899 |
| Robin  |   860 |
| Naruto |   960 |
| Nami   |   896 |
| Luffy  |   970 |
+--------+-------+

Summary

  • ORDER BY clause is used to sort data.
  • ASC stands for Ascending
  • DESC stand for descending
  • By default ORDER BY following the Ascending order.

Leave a Reply

Your email address will not be published. Required fields are marked *