Course contentsShow
← Data Science
Lesson 879 of 2,14522. SQL FoundationsFree lesson

Combining DISTINCT, ORDER BY, and LIMIT

Apply these clauses together for common patterns like 'top N unique values' and 'latest distinct entries'.

Combining DISTINCT, ORDER BY, and LIMIT

You'll learn how to chain these three clauses to answer powerful questions like "What are the top 5 unique product categories?" or "Show me the 10 most recent distinct customer cities."

The Power of the Trio

You've learned DISTINCT, ORDER BY, and LIMIT separately. Now it's time to combine them into patterns you'll use constantly in real-world data analysis. Think of it like a three-step filter: first remove duplicates, then arrange in meaningful order, then grab just the top slice you need.

Common Patterns

Pattern 1: Top N Unique Values

SELECT DISTINCT category
FROM products
ORDER BY category
LIMIT 5;

This finds unique product categories and shows only the first 5 alphabetically.

Pattern 2: Latest Distinct Entries

SELECT DISTINCT city
FROM orders
ORDER BY order_date DESC
LIMIT 10;

This identifies the 10 most recent cities where orders were placed (no duplicates even if a city had multiple recent orders).

Pattern 3: Highest Unique Scores

SELECT DISTINCT customer_rating
FROM reviews
ORDER BY customer_rating DESC
LIMIT 3;

Shows the top 3 distinct rating values—perfect for finding "what rating tiers exist?"

Execution Order Matters

SQL processes these in a specific sequence: DISTINCT removes duplicates first, then ORDER BY sorts the unique results, finally LIMIT takes the top rows. This order ensures you're always limiting after deduplication and sorting.

Key Takeaway: Combining DISTINCT, ORDER BY, and LIMIT lets you efficiently answer "top N unique" questions, a pattern essential for dashboards, reports, and exploratory analysis where you need focused, non-redundant results.