# 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.
2. Explain Like I'm 5
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 TraceDISTINCT & LIMIT Visual Simulator
SELECT DISTINCT country FROM users ORDER BY country;
SELECT * FROM users ORDER BY id DESC LIMIT 10 OFFSET 0;Active InputStep 1: Input & Parsing Stage
Initiating DISTINCT & LIMIT
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
An application fetches the top 5 countries where customers reside without duplicates.
| id | name | country |
|---|---|---|
| 1 | Alice | India |
| 2 | Bob | USA |
| 3 | Charlie | India |
| 4 | David | USA |
| 5 | Eve | Germany |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT DISTINCT country FROM users ORDER BY country;
SELECT id, name, created_at FROM users ORDER BY created_at DESC LIMIT 10 OFFSET 20;
SELECT DISTINCT ON (user_id) user_id, order_date, total_usd FROM orders ORDER BY user_id, order_date DESC;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| ORDER BY Requirement | LIMIT without ORDER BY produces non-deterministic results because relational engines do not guarantee physical row order. |
| All-Column Scope | SELECT DISTINCT a, b deduplicates unique combinations of (a, b), not just column a. |
| OFFSET Scaling Penalty | OFFSET 10000 forces the engine to compute and discard 10,000 rows before returning results. |
| Execution cost of DISTINCT | DISTINCT requires sorting or building an in-memory hash table across all projected columns to deduplicate. |
| OFFSET pagination performance degradation | OFFSET 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;
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
What is the primary drawback of using high OFFSET values (e.g. OFFSET 100000) for API pagination?