SQL - ORDER BY 子句

  • 简述

    SQLORDER BY子句用于根据一列或多列按升序或降序对数据进行排序。一些数据库默认按升序对查询结果进行排序。
  • 句法

    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 |
    +----+----------+-----+-----------+----------+
    
    以下代码块有一个示例,它将按 NAME 和 SALARY 升序对结果进行排序 -
    
    SQL> SELECT * FROM CUSTOMERS
       ORDER BY NAME, SALARY;
    
    这将产生以下结果 -
    
    +----+----------+-----+-----------+----------+
    | 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 |
    +----+----------+-----+-----------+----------+
    
    以下代码块有一个示例,它将按 NAME 降序对结果进行排序。
    
    SQL> SELECT * FROM CUSTOMERS
       ORDER BY NAME DESC;
    
    这将产生以下结果 -
    
    +----+----------+-----+-----------+----------+
    | 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 |
    +----+----------+-----+-----------+----------+