# ORDER BY: sort results
Sometimes you'd like your results to be returned in a specific order. By default, the order of results is always order of insertion (the order in which rows were entered into the table).
If you have a table of employees, you may want to sort them by years of experience, for example.
This is where the ORDER BY
clause comes into play:
SELECT * FROM employees ORDER BY years_experience DESC;
We have added two new things:
ORDER BY years_experience
tells the database to sort the results before giving them to us.DESC
tells the database to place the largest values at the top (descending order, high to low).
Alternatively we can use ASC
for ascending order, low to high.
TIP
You can skip ASC
or DESC
, and it defaults to ASC
.
# Relationship with WHERE
The order of clauses like WHERE
and ORDER BY
matters. ORDER BY
comes after WHERE
:
SELECT * FROM employees
WHERE years_experience < 10
ORDER BY years_experience DESC;
# Ordering by two or more columns
You can order by multiple columns by comma-separating the ORDER BY
columns:
... ORDER BY years_experience DESC, salary ASC;
Note that each column can have a different sorting order, if you'd like to get the employees with the most years of experience but lowest salary at the top.