Add the ORDER BY clause to a SELECT statement to sort results in ascending or descending order based on one or multiple columns.
Syntax Structure
SELECT
column1,
column2,
column3,
...
FROM
table_name
ORDER BY
column1 [ASC | DESC] [NULLS FIRST | NULLS LAST],
column2 [ASC | DESC] [NULLS FIRST | NULLS LAST];Code language: CSS (css)
Parameter Description
ASC: Sort in ascending order, default sort mode. ASC is used if omittedDESC: Sort in descending orderNULLS FIRST: Place NULL values before non‑NULL dataNULLS LAST: Place NULL values after non‑NULL data
- The
ORDER BYclause must always appear at the end of the SELECT statement. - Multi‑column sorting is supported; each column can have its own independent sorting rule.
Single‑Column Descending Sort
SELECT name, sex
FROM student
ORDER BY name DESC;
Oracle execution output:
SQL> select id, name from student order by name desc;
ID NAME
---------- ----------------
1 Tom
3 Lucy
2 JackCode language: JavaScript (javascript)
Multi‑Column Combined Sort
Sort by name descending first, then by sex ascending
SQL> select id, name from student order by name desc, sex asc;
ID NAME
---------- ----------------
1 Tom
3 Lucy
2 JackCode language: JavaScript (javascript)
NULL Value Control
-- Place NULL values at the very top
SELECT id,name,sex FROM student ORDER BY sex DESC NULLS FIRST;
-- Place NULL values at the very bottom
SELECT id,name,sex FROM student ORDER BY sex DESC NULLS LAST;Code language: PHP (php)
Sorting
Previous: Table insertion and query
Next: Distinct deduplication