ORDER BY 子句

2018-08-12 22:09 更新

SQL ORDER BY 子句

SQL ORDER BY 子句根據(jù)一列或者多列的值,按照升序或者降序排列數(shù)據(jù)。某些數(shù)據(jù)庫默認以升序排列查詢結(jié)果。

語法

ORDER BY 子句的基本語法如下所示:

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

ORDER BY 子句可以同時使用多個列作為排序條件。無論用哪一列作為排序條件,都要確保該列在存在。

示例:

考慮含有如下所示記錄的 CUSTOMERS 表:

    +----+----------+-----+-----------+----------+
    | ID | NAME     | AGE | ADDRESS   | SALARY   |
    +----+----------+-----+-----------+----------+
    |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    |  3 | kaushik  |  23 | Kota      |  2000.00 |
    |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    |  6 | Komal    |  22 | MP        |  4500.00 |
    |  7 | Muffy    |  24 | Indore    | 10000.00 |
    +----+----------+-----+-----------+----------+

下面的例子將查詢結(jié)果按照 NAME 和 SALARY 升序排列:

    SQL> SELECT * FROM CUSTOMERS
         ORDER BY NAME, SALARY;

結(jié)果如下所示:

    +----+----------+-----+-----------+----------+
    | ID | NAME     | AGE | ADDRESS   | SALARY   |
    +----+----------+-----+-----------+----------+
    |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    |  3 | kaushik  |  23 | Kota      |  2000.00 |
    |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    |  6 | Komal    |  22 | MP        |  4500.00 |
    |  7 | Muffy    |  24 | Indore    | 10000.00 |
    |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    +----+----------+-----+-----------+----------+

下面的例子將查詢結(jié)果按照 NAME 降序排列:

    SQL> SELECT * FROM CUSTOMERS
         ORDER BY NAME DESC;

結(jié)果如下所示:

    +----+----------+-----+-----------+----------+
    | ID | NAME     | AGE | ADDRESS   | SALARY   |
    +----+----------+-----+-----------+----------+
    |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    |  7 | Muffy    |  24 | Indore    | 10000.00 |
    |  6 | Komal    |  22 | MP        |  4500.00 |
    |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    |  3 | kaushik  |  23 | Kota      |  2000.00 |
    |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    +----+----------+-----+-----------+----------+
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號