The SQL ORDER BY
clause is used to sort the result set of a query by one or more columns. This clause is essential for organizing data in a specified order, making it easier to analyze and understand.
SELECT columns
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
The ORDER BY
clause sorts the records in ascending (ASC) or descending (DESC) order. If no order is specified, the default is ascending order.
Let's look at some examples of SQL ORDER BY clause queries using the employees
table:
SELECT first_name, last_name, hire_date
FROM employees
ORDER BY hire_date;
This query retrieves the first name, last name, and hire date of employees, sorted by the hire_date
column in ascending order.
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
This query retrieves the first name, last name, and salary of employees, sorted by the salary
column in descending order.
SELECT first_name, last_name, department_id, hire_date
FROM employees
ORDER BY department_id, hire_date DESC;
This query retrieves the first name, last name, department ID, and hire date of employees, sorted first by the department_id
column in ascending order and then by the hire_date
column in descending order.
SELECT first_name AS FirstName, last_name AS LastName, hire_date AS HireDate
FROM employees
ORDER BY HireDate;
This query retrieves the first name, last name, and hire date of employees with column aliases, sorted by the HireDate
column in ascending order.
SELECT first_name, last_name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;
This query retrieves the first name, last name, and annual salary (calculated as salary * 12
) of employees, sorted by the annual_salary
column in descending order.
The SQL ORDER BY
clause is a powerful tool for sorting query results in a specified order. Understanding how to use the ORDER BY
clause and its syntax is essential for writing effective queries that organize data in a meaningful way, making it easier to analyze and interpret.