SQL Order By
SQL ORDER BY
The ORDER BY clause is used to sort the result set of a query. By default, results are sorted in ascending order.
Basic Syntax
SELECT column1, column2 FROM table_name ORDER BY column1;
Ascending Order (ASC)
ASC sorts values from smallest to largest (A to Z, 0 to 9). ASC is the default, so you do not need to write it explicitly.
SELECT name, price FROM products ORDER BY price ASC;
Descending Order (DESC)
DESC sorts values from largest to smallest (Z to A, 9 to 0).
SELECT name, price FROM products ORDER BY price DESC;
Order By Multiple Columns
You can sort by more than one column. SQL sorts by the first column, then by the second if there are ties.
SELECT name, country, city FROM customers ORDER BY country ASC, city ASC;
Using ORDER BY with WHERE
ORDER BY is often combined with WHERE to filter and then sort the result.
SELECT name, price FROM products WHERE price > 100 ORDER BY price DESC;
Sorting Text and Numbers
Numeric columns are sorted numerically. Text columns are sorted alphabetically according to the database collation settings.
Sorting with Aliases
You can sort by a column alias defined in the SELECT clause.
SELECT name, price * quantity AS total FROM order_items ORDER BY total DESC;
NULL Sorting Behavior
The position of NULL values in sorting may vary between database systems. In many systems, NULL values appear first in ascending order and last in descending order.
Performance Note
Sorting large result sets can be expensive. Using indexes on frequently sorted columns can significantly improve performance.
Next Step
Continue with SQL AND to combine multiple conditions in a WHERE clause.