Sorting

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 omitted
  • DESC: Sort in descending order
  • NULLS FIRST: Place NULL values before non‑NULL data
  • NULLS LAST: Place NULL values after non‑NULL data
  1. The ORDER BY clause must always appear at the end of the SELECT statement.
  2. 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

Leave a Reply

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