Skip to content
Back to 50 Concepts
Topic 10 of 50query-executionBeginner

# Topic 10: DISTINCT & LIMIT

Eliminating duplicate rows with DISTINCT, PostgreSQL DISTINCT ON, and deterministic paging with LIMIT and OFFSET.

1. Definition

DISTINCT deduplicates matching rows from query results, while LIMIT and OFFSET restrict the quantity and starting position of returned tuples.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

DISTINCT is a duplicate filter: if you have five red marbles, it only hands you one. LIMIT is a plate size: no matter how much food is cooked, it only gives you 10 pieces.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

DISTINCT & LIMIT Visual Simulator

Step 1 of 3
SQL>SELECT DISTINCT country FROM users ORDER BY country; SELECT * FROM users ORDER BY id DESC LIMIT 10 OFFSET 0;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for DISTINCT & LIMIT
SQL Input

Initiating DISTINCT & LIMIT

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Line at an amusement park: LIMIT 5 lets the first 5 people in; OFFSET 100 makes the guard count 100 people and throw them out before letting the next 5 enter.

4. Real-World Example

An application fetches the top 5 countries where customers reside without duplicates.

Users Table
idnamecountry
1AliceIndia
2BobUSA
3CharlieIndia
4DavidUSA
5EveGermany
Relational walkthrough: SELECT DISTINCT country produces: India, USA, Germany.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Deduplicating values with DISTINCT
SELECT DISTINCT country FROM users ORDER BY country;
Sorts or hashes values in memory to discard duplicates.
Step 2: Pagination with LIMIT and OFFSET
SELECT id, name, created_at
FROM users
ORDER BY created_at DESC
LIMIT 10 OFFSET 20;
Always combine LIMIT with ORDER BY for deterministic results.
Step 3: PostgreSQL DISTINCT ON
SELECT DISTINCT ON (user_id) user_id, order_date, total_usd
FROM orders
ORDER BY user_id, order_date DESC;
Returns the single most recent order for each user.

6. Important Rules & Behaviors

RuleBehavioral Explanation
ORDER BY RequirementLIMIT without ORDER BY produces non-deterministic results because relational engines do not guarantee physical row order.
All-Column ScopeSELECT DISTINCT a, b deduplicates unique combinations of (a, b), not just column a.
OFFSET Scaling PenaltyOFFSET 10000 forces the engine to compute and discard 10,000 rows before returning results.
Execution cost of DISTINCTDISTINCT requires sorting or building an in-memory hash table across all projected columns to deduplicate.
OFFSET pagination performance degradationOFFSET N requires the engine to fetch and discard N rows, causing O(N) linear slowdown on deep pages.

7. Deep Dive: Offset Paging vs Keyset (Cursor) Pagination

OFFSET pagination gets progressively slower on deep pages because the database must scan all preceding rows. Keyset pagination uses indexed WHERE conditions to achieve constant O(1) page lookup times.

-- Bad for deep pages (O(N) cost):
SELECT * FROM orders ORDER BY id LIMIT 20 OFFSET 50000;

-- Good Keyset Pagination (O(log N) index seek):
SELECT * FROM orders WHERE id > 50000 ORDER BY id LIMIT 20;
Caution: Never use high OFFSET values on multi-million row tables in production APIs.

8. Advantages & Disadvantages

Advantages

  • •DISTINCT eliminates unwanted duplicate records from reports.
  • •LIMIT protects network bandwidth and API response sizes.
  • •DISTINCT ON cleanly solves "greatest-n-per-group" query problems.

Disadvantages & Trade-offs

  • •DISTINCT triggers expensive in-memory sort or hash operations.
  • •High OFFSET queries cause high disk I/O and CPU waste.

9. Common Interview Questions

Q1.How does the database engine physically execute DISTINCT under the hood?

The Cost-Based Optimizer chooses between two physical algorithms: 1. Hash Aggregate: the engine hashes each row into an in-memory hash table; duplicate hashes with identical values are discarded. 2. Unique Sort: the engine sorts the entire result set (using QuickSort or external merge sort) and then streams rows while discarding adjacent duplicates. Hash Aggregate is faster if the unique set fits in work_mem.

Q2.What is the critical performance bug of OFFSET pagination (LIMIT 20 OFFSET 1000000)?

OFFSET 1,000,000 tells the engine to read 1,000,020 rows from disk, sort them, count up to 1,000,000, throw away the first 1,000,000 rows, and return only the last 20 rows. As page numbers increase, response times degrade linearly from milliseconds to seconds, causing massive disk I/O and CPU burn.

Q3.How does Keyset (Cursor-Based) Pagination solve the OFFSET performance problem?

Keyset pagination replaces OFFSET with a SARGable WHERE filter on an indexed column (like id or created_at): SELECT * FROM posts WHERE id > last_seen_id ORDER BY id ASC LIMIT 20; Because id is indexed, the engine performs an O(log N) B-Tree seek directly to the 1,000,001st row and reads exactly 20 rows, remaining ultra-fast (0.1 ms) even on page 1,000,000.

Q4.What is PostgreSQL’s DISTINCT ON (col) and how is it used in interviews?

DISTINCT ON is a powerful PostgreSQL extension that keeps only the first row of each group based on the ORDER BY clause. It is the cleanest way to solve the classic "find the latest order per customer" interview question without writing complex correlated subqueries or window functions.

-- Get the single most recent order for each customer:
SELECT DISTINCT ON (customer_id) customer_id, order_id, total, created_at
FROM orders
ORDER BY customer_id, created_at DESC;

Q5.Why is LIMIT without an ORDER BY clause dangerous in production?

Relational tables are unordered heaps. Without an explicit ORDER BY clause, the database does not guarantee any deterministic order. Running SELECT * FROM users LIMIT 10 twice in a row can return completely different sets of users if disk pages are cached differently or parallel scan workers finish in varying order.

10. Interview-Ready Answer

“DISTINCT removes duplicate tuples using in-memory hash or sort aggregates, while LIMIT bounds response sizes. To maintain deterministic paging and sub-millisecond latency, always combine LIMIT with ORDER BY and use keyset pagination instead of high OFFSETs.”

11. Quick Test

Scenario Question:

What is the primary drawback of using high OFFSET values (e.g. OFFSET 100000) for API pagination?

Select your answer: