Chapter 22: PostgreSQL LIMIT

Part 1: What is the LIMIT Clause?

The LIMIT clause restricts the number of rows returned by a query. It’s typically used with ORDER BY to get meaningful subsets like “top 10 bestsellers” or “most recent 5 orders.”

The Basic Syntax

sql

The row_count specifies the maximum number of rows to return.

Part 2: Setting Up Our Example Data

Let’s create a comprehensive dataset to explore all the ways LIMIT can be used:

sql

Part 3: Basic LIMIT Usage

1. Simple LIMIT – First N Rows

The most basic use – get the first 5 products from the table:

sql

Result:

product_id name price category
1 Wireless Headphones 89.99 Electronics
2 Gaming Mouse 49.99 Electronics
3 Mechanical Keyboard 129.99 Electronics
4 4K Monitor 399.99 Electronics
5 USB-C Hub 39.99 Electronics

Important: Without ORDER BY, the rows are returned in whatever order PostgreSQL finds them (usually insertion order, but not guaranteed). This is rarely what you want!

2. LIMIT with ORDER BY – Getting Meaningful Results

This is the real power of LIMIT – combine it with ORDER BY to get top or bottom results:

sql

Result:

name price category
Standing Desk 499.99 Furniture
4K Monitor 399.99 Electronics
Desk Chair 249.99 Furniture
Microwave 199.99 Appliances
Office Cabinet 189.99 Furniture
sql

Result:

name price category
Paper Clips (box) 2.99 Stationery
Notebook 3.99 Stationery
Lip Balm 4.99 Beauty
Fish Food 5.99 Pets
Pen Set 7.99 Stationery

3. LIMIT with WHERE – Filtered Top Results

sql

Result:

name rating price
Mechanical Keyboard 4.8 129.99
Wireless Headphones 4.7 89.99
4K Monitor 4.6 399.99
Gaming Mouse 4.5 49.99
USB-C Hub 4.3 39.99

Part 4: LIMIT with OFFSET – Pagination

This is one of the most common real-world uses of LIMIT – implementing pagination. The OFFSET clause skips a specified number of rows before starting to return rows.

Basic Syntax with OFFSET

sql

1. Simple Pagination

Show products 11-20 (page 2 with 10 items per page):

sql

Result (rows 11-20):

product_id name price category
11 Desk Chair 249.99 Furniture
12 Standing Desk 499.99 Furniture
13 Bookshelf 159.99 Furniture
14 Lamp 45.99 Furniture
15 Office Cabinet 189.99 Furniture
16 Running Shoes 89.99 Sports
17 Yoga Mat 24.99 Sports
18 Dumbbells Set 79.99 Sports
19 Water Bottle 14.99 Sports
20 Gym Bag 39.99 Sports

2. Building a Pagination System

Here’s how you’d typically implement pagination in an application:

sql

The formula is simple: OFFSET = (page_number - 1) * page_size

3. Pagination with Custom Sorting

sql

4. Getting Total Count for Pagination

When implementing pagination, you usually need to know the total number of pages:

sql

Part 5: LIMIT with Different Data Types

1. LIMIT with Dates – Most Recent Items

sql

Result:

name category created_date
Wall Clock Home 2024-02-01
Paper Clips (box) Stationery 2024-01-30
Hat Clothing 2024-01-29
Lip Balm Beauty 2024-01-27
The Hobbit Books 2024-01-27

2. LIMIT with Aggregates – Top Categories

sql

Result:

category product_count
Electronics 5
Furniture 5
Sports 5

(Many categories have 5 products in our sample)

3. LIMIT with NULL Values

sql

Result:

name price
Unknown Product 1 NULL
Unknown Product 2 NULL
Unknown Product 3 25.99

Part 6: LIMIT with DISTINCT

When using DISTINCT, LIMIT applies after duplicates are removed:

sql

Result:

category
Appliances
Beauty
Books
Clothing
Electronics

Important: ORDER BY with DISTINCT

When using DISTINCT, the ORDER BY columns must appear in the SELECT list:

sql

Part 7: LIMIT with JOINS

LIMIT works beautifully with joined tables. Let’s create an orders table for more examples:

sql

Result:

order_date customer_name product_name quantity total_amount
2024-02-10 Stephen King Dog Food (10lb) 1 29.99
2024-02-10 Taylor Swift Cat Bed 2 69.98
2024-02-09 Quentin Tarantino Face Cream 2 49.98
2024-02-09 Ringo Starr Lip Balm 4 19.96
2024-02-08 Paul McCartney Shampoo 1 8.99

Part 8: Advanced LIMIT Techniques

1. LIMIT with Window Functions

Get top 3 products by rating in each category:

sql

Result (partial):

name category rating
Air Fryer Appliances 4.8
Blender Appliances 4.6
Microwave Appliances 4.5
Mechanical Keyboard Electronics 4.8
Wireless Headphones Electronics 4.7
4K Monitor Electronics 4.6

This is more powerful than simple LIMIT because it gives you top N per group.

2. Random Sampling with LIMIT

Get 5 random products:

sql

Each time you run this, you get a different set of 5 products.

3. LIMIT with Subqueries

Find products that are more expensive than the 5th most expensive product:

sql

4. LIMIT with UNION

Get top 3 from two different categories:

sql

Part 9: Performance Considerations

1. LIMIT with Indexes

LIMIT can be extremely fast when combined with appropriate indexes:

sql

2. How PostgreSQL Optimizes LIMIT

When you use ORDER BY ... LIMIT n, PostgreSQL tries to avoid sorting the entire table. If an index provides the ordered data, it can just scan the index until it finds n rows:

sql

Look for “Limit” in the plan – it might show that PostgreSQL only needed to scan a small portion of an index.

3. Large OFFSET Performance

Large offsets can be slow because PostgreSQL still has to count through all the skipped rows:

sql

For large offsets, consider:

  • Using keyset pagination (WHERE price < last_seen_price)

  • Materialized views

  • Caching

4. Keyset Pagination (Better for Large Offsets)

Instead of OFFSET, use a WHERE clause based on the last seen value:

sql

This scales much better than OFFSET for large datasets.

Part 10: Real-World Examples

Example 1: E-commerce Product Listing Page

sql

Example 2: Admin Dashboard – Recent Orders with Issues

sql

Example 3: Best Sellers Report

sql

Example 4: Inventory Alerts

sql

Example 5: Customer Purchase History

sql

Part 11: Common Mistakes and How to Avoid Them

Mistake 1: Using LIMIT Without ORDER BY

sql

Mistake 2: Assuming OFFSET is Zero-Based

sql

Mistake 3: Large OFFSET Values

sql

Mistake 4: Forgetting NULL Handling

sql

Mistake 5: Using LIMIT in Subqueries Incorrectly

sql

Summary: The LIMIT Philosophy

The LIMIT clause is your tool for controlling data volume. Master these concepts:

  1. Basic LIMIT – Get first N rows

  2. LIMIT with ORDER BY – Get meaningful top/bottom results

  3. Pagination with OFFSET – Navigate through data page by page

  4. Performance awareness – Indexes and large offset considerations

  5. Advanced techniques – Window functions for “top N per group”

Remember the query execution order:

  1. FROM/JOIN – Get all possible rows

  2. WHERE – Filter rows

  3. GROUP BY – Group rows

  4. HAVING – Filter groups

  5. SELECT – Compute expressions

  6. ORDER BY – Sort results

  7. LIMIT/OFFSET – Trim results – HERE!

This means LIMIT works on the final, sorted result set. It’s the very last operation.

Key takeaways:

  • Always use ORDER BY with LIMIT unless you truly don’t care about order

  • OFFSET is great for pagination but watch performance with large offsets

  • Index the columns you sort by for fast LIMIT queries

  • Consider keyset pagination for better performance with large datasets

  • Use window functions when you need “top N per group”

The LIMIT clause transforms your database from a firehose of data into a controlled faucet, letting you take exactly what you need, when you need it. Whether you’re building user interfaces, generating reports, or analyzing data, LIMIT is essential for creating responsive, efficient applications.

Would you like me to elaborate on any specific aspect of LIMIT, such as more complex pagination strategies, performance optimization, or integration with other SQL features?

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *