ORDER BY
ORDER BY in SQL is a clause used to sort the result set from a SQL query in either ascending (ASC) or descending (DESC) order according to one or more columns.
Example
SELECT *FROM EmployeesORDER BY LastName ASC;
Output
+------+----------+------------+| EmpID| FirstName| LastName|+------+----------+------------+| 3 | David| Adams || 1 | John | Brown || 4 | Chris| Smith || 2 | Alice| White |+------+----------+------------+
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
SELECT name, ageFROM employeesORDER BY age;
Output
| name | age ||-------|-----|| John | 23 || Jane | 26 || Peter | 30 || Amy | 33 |
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
SELECT * FROM EmployeesORDER BY LastName ASC;
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 | NULL
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
SELECT * FROM EmployeesORDER BY Last_name ASC;
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
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
SELECT * FROM CustomersORDER BY Country;
Output
+----+---------+-----------+| ID | Name | Country |+----+---------+-----------+| 3 | Antonio | Argentina || 1 | Alfreds | Germany || 2 | Maria | Mexico |+----+---------+-----------+
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.