MyMisPal
← SQL lessons
Lesson 4 of 12

ORDER BY & LIMIT: sorting

ORDER BY sorts the result. The default is ascending ASC; write DESC for descending. You can sort by several columns.

SQL
SELECT first_name, dept_id, salary
FROM employees
ORDER BY dept_id ASC, salary DESC;

LIMIT sets how many rows you get. Combined with sorting it gives you the top or bottom values:

SQL
SELECT first_name, hire_date
FROM employees
ORDER BY hire_date
LIMIT 3;
In MySQLLIMIT is the same in MySQL. SQL Server uses SELECT TOP 3 ... and Oracle uses FETCH FIRST 3 ROWS ONLY.

Exercises

Exercise 1

Show the 3 most expensive products: name and price, highest first.

Exercise 2

Show name and signup_date for all customers, newest sign-up first.

Spotted a mistake on this page, or have an idea to improve the site?