Filtering Data with WHERE Clause and Operators

In this lesson, you'll learn how to refine your SQL queries by sorting the results using `ORDER BY` and limiting the number of results returned using `LIMIT`. These techniques are crucial for making sense of large marketing datasets and extracting the most relevant information quickly.

Learning Objectives

  • Understand the purpose of the `ORDER BY` clause and how to use it to sort results.
  • Learn how to specify the sorting order (ascending and descending).
  • Grasp the function of the `LIMIT` clause and how to restrict the number of rows returned.
  • Combine `ORDER BY` and `LIMIT` to extract the most important data from a query.

Text-to-Speech

Listen to the lesson content

Lesson Content

Sorting Results with ORDER BY

The ORDER BY clause allows you to sort the results of your query based on one or more columns. By default, it sorts in ascending order (from smallest to largest or alphabetically). You specify the column(s) you want to sort by after ORDER BY.

Example: Suppose you have a table called campaign_performance with columns like campaign_name and clicks. To sort the campaigns by the number of clicks in ascending order, you'd use:

SELECT campaign_name, clicks
FROM campaign_performance
ORDER BY clicks;

To sort in descending order (largest to smallest), use the DESC keyword:

SELECT campaign_name, clicks
FROM campaign_performance
ORDER BY clicks DESC;

You can also sort by multiple columns. The first column listed after ORDER BY is the primary sort, and subsequent columns are used for ties.

SELECT campaign_name, clicks, cost
FROM campaign_performance
ORDER BY clicks DESC, cost ASC; -- Sort by clicks descending, then cost ascending if clicks are the same

Limiting Results with LIMIT

The LIMIT clause restricts the number of rows returned by a query. It's useful when you only need the top few results (e.g., top-performing campaigns) or want to see a sample of the data. Place LIMIT at the end of your query.

Example: To see only the top 5 campaigns by clicks:

SELECT campaign_name, clicks
FROM campaign_performance
ORDER BY clicks DESC
LIMIT 5;

You can also use LIMIT with an offset to retrieve a specific "page" of results. OFFSET specifies the starting row.

SELECT campaign_name, clicks
FROM campaign_performance
ORDER BY clicks DESC
LIMIT 5 OFFSET 10; -- Gets the next 5 after skipping the first 10 rows (rows 11-15)

Combining ORDER BY and LIMIT

The true power comes from combining ORDER BY and LIMIT. This allows you to easily identify top performers, worst performers, or get a small sample of the most relevant data. The ORDER BY clause always comes before LIMIT.

Example: Find the 3 most expensive campaigns (highest cost):

SELECT campaign_name, cost
FROM campaign_performance
ORDER BY cost DESC
LIMIT 3;
Progress
0%