ORDER BY
Example
Section titled “Example”SELECT *FROM EmployeesORDER BY LastName ASC;Output
Section titled “Output”+------+----------+------------+| EmpID| FirstName| LastName|+------+----------+------------+| 3 | David| Adams || 1 | John | Brown || 4 | Chris| Smith || 2 | Alice| White |+------+----------+------------+Explanation
Section titled “Explanation”The query selects all records from the Employees table and orders them in ascending order (ASC) by the LastName column. Therefore, the result set is sorted from A to Z based on the employees’ last names. In case ASC is not specified, the sorting default is ascending order.
Example
Section titled “Example”SELECT name, ageFROM employeesORDER BY age;Output
Section titled “Output”| name | age ||-------|-----|| John | 23 || Jane | 26 || Peter | 30 || Amy | 33 |Explanation
Section titled “Explanation”The Example provided is a SQL statement that retrieves employee names and their respective ages from the employees table. It organizes the returned data in ascending order based on the employees’ ages. The ORDER BY clause accomplishes this sorting.
Example
Section titled “Example”SELECT * FROM EmployeesORDER BY LastName ASC;Output
Section titled “Output”EmployeeID | LastName | FirstName | BirthDate | Photo | Notes------------|------------|-------------|-------------|---------|---------4 | Baker | Allan | 1958-09-05 | NULL | NULL1 | Smith | John | 1965-12-08 | NULL | NULL2 | White | Jane | 1980-05-29 | NULL | NULL3 | Johnson | Fred | 1970-07-18 | NULL | NULLExplanation
Section titled “Explanation”The SELECT * FROM Employees statement is used to select all records from the Employees table.
The ORDER BY LastName ASC clause sorts the result set by the LastName in ascending order. If LastName were the same for two employees, it uses the order they appear in the table.
Example
Section titled “Example”SELECT * FROM EmployeesORDER BY Last_name ASC;Output
Section titled “Output”| Employee_ID | Last_Name | First_Name | Salary ||-------------|-----------|------------|--------|| 4 | Abrams | Jake | 50000 || 2 | Brown | Emily | 65000 || 1 | Carson | David | 70000 || 3 | Smith | Lisa | 55000 |Explanation
Section titled “Explanation”The SELECT statement orders the rows in ascending order (ASC) by the Last_name column. If two or more last names are the same, it orders these rows based on their positions in the database.
Example
Section titled “Example”SELECT * FROM CustomersORDER BY Country;Output
Section titled “Output”+----+---------+-----------+| ID | Name | Country |+----+---------+-----------+| 3 | Antonio | Argentina || 1 | Alfreds | Germany || 2 | Maria | Mexico |+----+---------+-----------+Explanation
Section titled “Explanation”The SQL ORDER BY keyword sorts the result-set in ascending (default) or descending order. In this instance, the query is ordering the customers by their respective countries in ascending order.