PostgreSQL ORDER BY
The ORDER BY
clause is used to sort the result set based on one or more columns. By default, results are sorted in ascending order.
Key Topics
1. Basic Usage
SELECT *
FROM employees
ORDER BY last_name ASC;
This sorts employees in ascending order by their last_name
.
2. Sorting by Multiple Columns
SELECT first_name, last_name, department
FROM employees
ORDER BY department, last_name DESC;
This sorts first by department
(ascending by default), then by last_name
descending within each department.
Best Practices
- Index columns used in
ORDER BY
when performance is critical. - Use ascending (
ASC
) or descending (DESC
) order to get the desired sorting.
Key Takeaways
ORDER BY
organizes query results for easier readability and data analysis.- You can specify multiple columns with different sort directions.