Interview Query

ORDER BY and LIMIT

After selecting the table we need, there are two handy operations we can perform on the output.

One is ORDER BY, which allows us to order the rows in our table according to a specific column.

The other is LIMIT, which limits the number of rows a query will return.

ORDER BY

Let’s say we have a table called employees with the following data:

EmployeeID Name Department Salary
1 John Sales 52000
2 Mary Marketing 48000
3 Bob Engineering 50000
4 Rachel Sales 51000
5 Steve Marketing 49000
6 Maria Engineering 53000

Then:

SELECT * FROM employees

would return the table employees.

If we want to, we can add an ORDER BY clause at the end of our query to reorder the rows in our output.

For example,

SELECT * FROM employees
ORDER BY Salary

will return the following table:

EmployeeID Name Department Salary
2 Mary Marketing 48000
5 Steve Marketing 49000
3 Bob Engineering 50000
4 Rachel Sales 51000
1 John Sales 52000
6 Maria Engineering 53000

By default, ORDER BY sorts our values in ascending order. We must specify the DESC keyword after the column name if we want SQL to order values in descending order.

For example,

SELECT * FROM employees
ORDER BY Name DESC

will sort the table alphabetically by name, in descending order:

EmployeeID Name Department Salary
5 Steve Marketing 49000
4 Rachel Sales 51000
2 Mary Marketing 48000
6 Maria Engineering 53000
1 John Sales 52000
3 Bob Engineering 50000

LIMIT

The LIMIT clause simply limits the number of rows a query will return. For example, putting LIMIT 3 at the end of a query would make SQL only return the first three rows of the query’s result.

We can combine it with the ORDER BY clause to find the 3 employees with the highest salaries.

SELECT * FROM employees
ORDER BY Salary DESC
LIMIT 3

will give us the output:

EmployeeID Name Department Salary
6 Maria Engineering 53000
1 John Sales 52000
4 Rachel Sales 51000

What we learned so far:

Example query

SELECT first_name, SUM(salary)
FROM employees
	JOIN sales
ON employee.id = sales.employeeID

GROUP BY employee.id
HAVING COUNT(*) > 1
WHERE salary > 7500 AND last_name != "Williams"

ORDER BY salary DESC
LIMIT 5

Execution order

  1. FROM -> Gets input tables
  2. JOIN … ON -> Merges input tables
  3. WHERE -> Filters rows according to condition
  4. GROUP BY -> Separates into smaller tables
  5. HAVING -> Filters smaller tables according to condition
  6. SELECT -> Selects the columns we need (and integrates smaller tables)
  7. SUM() and aggregate functions or numerical operations performed on output.
  8. ORDER BY -> Orders rows
  9. LIMIT -> Limits the number of rows returned.

0%

Completed

You have 56 sections remaining on this learning path.

Loading pricing options