SQL order by
Created By: chatGPT
In SQL, the ORDER BY clause is used to sort the result set of a query by one or more columns. You can specify whether the sorting should be in ascending (
ASC
) or descending (DESC
) order. By default, the ORDER BY clause sorts the records in ascending order.SELECT * FROM employees
ORDER BY last_name ASC;
To sort the records by multiple columns, you can list the columns separated by commas. The order of the columns in the clause determines the priority of sorting.
SELECT * FROM employees
ORDER BY department_id ASC, last_name DESC;
You can also utilize expressions in the ORDER BY clause, including calculations or case statements. This allows for more complex sorting logic.
SELECT *, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;
If you want to sort based on a calculated field or a function that is applied to a column, you can do so within the ORDER BY clause.
SELECT employee_id, UPPER(first_name) as upper_first_name
FROM employees
ORDER BY upper_first_name ASC;
It’s important to remember that if you’re using an ORDER BY clause in a subquery, the sort order might not be preserved when the outer query is executed unless specified again.
SELECT *
FROM (
SELECT * FROM employees
ORDER BY hire_date DESC
) AS recent_hires
ORDER BY last_name ASC;