Sorting and Ordering: ORDER BY and LIMIT

This lesson focuses on refining your SQL queries by learning how to sort and limit the results you get. You'll master the `ORDER BY` clause to arrange data in a specific order and the `LIMIT` clause to control the number of rows returned, making data analysis much more efficient.

Learning Objectives

  • Understand how to use the `ORDER BY` clause to sort query results.
  • Learn to sort data in ascending and descending order using `ORDER BY`.
  • Know how to use the `LIMIT` clause to restrict the number of rows returned.
  • Apply both `ORDER BY` and `LIMIT` clauses in combination to extract specific data subsets.

Text-to-Speech

Listen to the lesson content

Lesson Content

Introduction to Sorting with ORDER BY

When you execute a SELECT statement, the database typically returns results in an arbitrary order. The ORDER BY clause allows you to specify the column(s) by which you want to sort the results. The default sorting order is ascending (from smallest to largest for numbers, or alphabetically for text).

Example:
Suppose you have a table named employees with columns like employee_id, first_name, last_name, and salary. To sort employees by their last name alphabetically, you'd use:

SELECT employee_id, first_name, last_name
FROM employees
ORDER BY last_name;

Sorting in Descending Order

To sort the results in descending order (largest to smallest or reverse alphabetical order), you can use the DESC keyword after the column name in the ORDER BY clause.

Example:
To sort employees by salary in descending order (highest salary first):

SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary DESC;

To sort by multiple columns, you can specify them separated by commas. For example, sort by last name, and then by first name (both in ascending order):

SELECT employee_id, first_name, last_name
FROM employees
ORDER BY last_name, first_name;

Limiting Results with LIMIT

The LIMIT clause restricts the number of rows returned by a query. This is particularly useful when you only need to see the top few results (e.g., the top 10 highest-paid employees) or to paginate through a large dataset. The LIMIT clause is usually placed at the end of the query.

Example:
To retrieve only the top 3 highest-paid employees:

SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;

To select records starting at a certain offset use the OFFSET keyword.

SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3 OFFSET 2;

This will return the 3 rows starting from row number 3 (0-indexed).

Combining ORDER BY and LIMIT

You can combine ORDER BY and LIMIT to get specific subsets of your sorted data. This is a common and powerful technique.

Example:
To get the 5 employees with the lowest salaries:

SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary ASC
LIMIT 5;
Progress
0%