The ORDER BY
clause in SQL allows you to sort the results of your queries in a specific order. This is incredibly useful for organizing your data and making it easier to analyze.
ASC
)The ASC
keyword sorts the data in ascending order, from smallest to largest.
SELECT *
FROM customers
ORDER BY last_name ASC;
This query would return all customer data, sorted alphabetically by the last_name
column.
DESC
)The DESC
keyword sorts the data in descending order, from largest to smallest.
SELECT *
FROM orders
ORDER BY order_date DESC;
This query would return all order data, sorted by the order_date
column, with the most recent orders at the top.
You can order by multiple columns by listing them after ORDER BY
, separated by commas.
SELECT *
FROM products
ORDER BY category ASC, price DESC;
This query would first sort products by category
in ascending order, then within each category, sort by price
in descending order.
The ORDER BY
clause can be used to sort by any column type, including text columns.
SELECT *
FROM employees
ORDER BY department ASC, first_name DESC;
This query would first sort employees by department
in ascending order, then within each department, sort by first_name
in descending order.
By default, NULL
values are considered the smallest value when sorting in ascending order, and the largest value when sorting in descending order.
The ORDER BY
clause is a fundamental part of SQL. It allows you to present your data in a meaningful and organized way, making it easier to analyze and understand.