SQL ORDER BY
SQL ORDER BY Clause used to sorting SQL result set either ascending or descending order.
SQL ORDER BY Clause default record set sorting ascending order. Using DESC keyword to result set sorting in descending order.
Syntax
Considering following syntax that help you to understanding ORDER BY clause,
SELECT
column_name1, column_name2, ...
FROM table_name
[ WHERE condition ]
ORDER BY column_name1, column_name2 [ ASC | DESC ];
Example
We have following employee_hour
table that store weekday hours for each employee:
SQL> SELECT * FROM employee_hour;
NAME DAY HOURS
-------------------- ---------- ----------
Opal Kole Monday 8
Max Miller Monday 8
Beccaa Moss Monday 8
Paul Singh Monday 9
Opal Kole Tuesday 9
Max Miller Tuesday 6
Beccaa Moss Tuesday 10
Paul Singh Tuesday 8
Opal Kole Wednesday 7
Max Miller Wednesday 9
Beccaa Moss Wednesday 11
Paul Singh Wednesday 12
12 rows selected.
Example
SQL> SELECT *
FROM employee_hour
ORDER BY hours;
NAME DAY HOURS
-------------------- ---------- ----------
Max Miller Tuesday 6
Opal Kole Wednesday 7
Max Miller Monday 8
Beccaa Moss Monday 8
Opal Kole Monday 8
Paul Singh Tuesday 8
Paul Singh Monday 9
Opal Kole Tuesday 9
Max Miller Wednesday 9
Beccaa Moss Tuesday 10
Beccaa Moss Wednesday 11
Paul Singh Wednesday 12
12 rows selected.
ORDER BY clause apply on hours
column, result set return into ascending order.
Example
SQL> SELECT *
FROM employee_hour
ORDER BY hours DESC;
NAME DAY HOURS
-------------------- ---------- ----------
Paul Singh Wednesday 12
Beccaa Moss Wednesday 11
Beccaa Moss Tuesday 10
Paul Singh Monday 9
Opal Kole Tuesday 9
Max Miller Wednesday 9
Opal Kole Monday 8
Max Miller Monday 8
Paul Singh Tuesday 8
Beccaa Moss Monday 8
Opal Kole Wednesday 7
Max Miller Tuesday 6
12 rows selected.
Same thing as above but ORDER BY clause apply on hours
column, result set return into descending order.