[SQL] Mastering the LIMIT Clause: Control Displayed Rows from Basics to Pagination
âTop 5 New Arrivals,â âTop 10 Popular Articles,â âFirst Page of Search Resultsâ⊠On websites and apps, it's very common to display only a portion of a large data set. The powerful SQL clause that makes this possible is LIMIT.
This article is aimed at web creators and explains everything from the basics of the LIMIT clause to implementing the essential web development technique of pagination. It includes rich sample code and even an interactive execution environment you can copy and paste. Try it hands-on and equip yourself with this powerful tool to manipulate data smartly!
Warm-up First! We'll Use Sample Data Again
Before diving in, weâll once again use the product table (products) from a fictional online store called âWeb Creator's Mart.â If you've read our previous ORDER BY article, it may look familiar to you.
The SQL below creates the table and inserts data. You can try this in your environment or use it in the âinteractive execution environmentâ weâll show later. Take a moment to review it.
-- Create product table
CREATE TABLE products (
id INT,
name VARCHAR(255),
category VARCHAR(255),
price INT,
release_date DATE
);
-- Insert sample data (7 rows)
INSERT INTO products (id, name, category, price, release_date) VALUES
(1, 'Fluffy Cushion', 'Interior', 3200, '2023-04-15'),
(2, 'Focus Ear Muffs', 'Gadget', 7800, '2023-11-01'),
(3, 'Idea Spark Notebook', 'Stationery', 1200, '2022-08-20'),
(4, 'Glowing Keyboard', 'Gadget', 15000, '2023-06-30'),
(5, 'Ultimate Comfort Chair', 'Interior', 32000, '2022-11-10'),
(6, 'Smooth Ballpoint Pen', 'Stationery', 1200, '2023-09-01'),
(7, 'Creator Mug Cup', 'Tableware', 2500, '2023-04-15');
All set? Letâs jump into the world of the LIMIT clause!
Basics of the LIMIT Clause: Specify the Number of Rows to Retrieve
The simplest use of the LIMIT clause is to specify the maximum number of records (rows) to retrieve. The syntax is very simple â just add LIMIT number at the end of your SELECT statement.
For example, letâs try retrieving just 3 rows from the products table.
SELECT * FROM products LIMIT 3;
When executed, this returns the first 3 rows in the order they are stored in the table. It's very intuitive. However, there's one important caveat â without any ordering, thereâs no guarantee on which 3 rows youâll get. The order may vary each time depending on the internal behavior of the database.
The true power of the LIMIT clause is unleashed when combined with ORDER BY, which we covered in the previous article.
Power Combo! Use ORDER BY + LIMIT to Get the âTop Nâ Rows
Getting the âTop N rowsâ â such as âTop 3 most expensive productsâ or âTop 5 newest releasesâ â is a common requirement on websites. You can achieve this by first sorting the data using ORDER BY and then limiting the results with LIMIT.
Letâs retrieve the top 3 most expensive products. Use ORDER BY price DESC to sort in descending order of price, and then apply LIMIT 3 to get the top 3.
-- Get the top 3 most expensive products
SELECT * FROM products ORDER BY price DESC LIMIT 3;
How did it go? You should see âUltimate Comfort Chairâ, âGlowing Keyboardâ, and âFocus Ear Muffsâ in that order. The key pattern here is to use ORDER BY to determine the order, then apply LIMIT to trim it. Remember to always use them together.
Letâs also get the âTop 2 newest productsâ. This time, we sort by release date (release_date).
-- Get the top 2 newest products by release date
SELECT * FROM products ORDER BY release_date DESC LIMIT 2;
Shift the Starting Point with OFFSET
The LIMIT clause has a powerful partner â OFFSET. As the name suggests, OFFSET specifies âhow many rows to skip from the beginningâ.
For example, suppose you want to exclude the top product and fetch only the 2nd and 3rd most expensive items. OFFSET makes this possible.
-- Skip the first result and retrieve the next 2 most expensive products
SELECT * FROM products ORDER BY price DESC LIMIT 2 OFFSET 1;
This SQL works as follows:
ORDER BY price DESCsorts the products in descending price order.OFFSET 1skips the first product (the most expensive).LIMIT 2fetches the next 2 items (2nd and 3rd).
This combination of LIMIT and OFFSET is at the heart of the âpaginationâ technique weâll explore next.
Advanced: Implement Pagination Using LIMIT and OFFSET
Pagination is a technique used to split large data sets â such as blog posts or product lists â across multiple pages. Youâve probably seen pagers like â1, 2, 3, 4, 5, ... Nextâ on many websites.
Pagination is implemented using LIMIT and OFFSET. Letâs say you want to show 3 items per page.
- Page 1: retrieve the first 3 items (skip 0 rows)
- Page 2: skip the first 3 items, then retrieve the next 3 items
- Page 3: skip the first 6 items, then retrieve the next 3 items
The SQL for each page looks like this. To keep the order consistent, weâll sort by id.
ăSQL for Page 1ă
-- Page 1: skip 0 rows, get 3
SELECT * FROM products ORDER BY id LIMIT 3 OFFSET 0;
ăSQL for Page 2ă
-- Page 2: skip 3 rows, get 3
SELECT * FROM products ORDER BY id LIMIT 3 OFFSET 3;
ăSQL for Page 3ă
-- Page 3: skip 6 rows, get 3
SELECT * FROM products ORDER BY id LIMIT 3 OFFSET 6;
Notice something? The LIMIT value (items per page) is always 3. The OFFSET value increases as 0, 3, 6, .... You can calculate the OFFSET with:
OFFSET = (current page - 1) Ă items per page
By implementing this logic in your program, you can build dynamic pagination easily. And donât worry â in the next section, weâll show you a live interactive demo!
ăTry it out!ăExecute SQL directly in your browser
Thank you for waiting! We have prepared an interactive environment where you can run SQL directly in your browser. With this, you can try out various LIMIT clause patterns discussed in this article by yourself.
Copy the entire code below, save it as a file such as index.html, and open it in your browser. Paste the sample SQL from this article into the text area and click the âRun SQLâ button!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SQL Practice Environment</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
h1, h2 { color: #444; border-bottom: 2px solid #eee; padding-bottom: 0.3em;}
textarea { width: 100%; height: 150px; font-family: monospace; font-size: 16px; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; margin-bottom: 1rem; }
button { background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
button:hover { background-color: #0056b3; }
#result-container { margin-top: 1.5rem; min-height: 100px;}
table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
th { background-color: #f8f8f8; }
#error-message { color: red; font-weight: bold; margin-top: 1rem; }
</style>
</head>
<body>
<h1>Learn by running SQL! LIMIT Clause Practice</h1>
<p>Enter an SQL statement in the text area below and click the âRun SQLâ button. Try out the various SQL examples introduced in the article!</p>
<textarea id="sql-input">-- Paste SQL here and run!
-- Example: Top 3 most expensive products
SELECT * FROM products ORDER BY price DESC LIMIT 3;</textarea>
<button onclick="executeQuery()">Run SQL</button>
<h2>Execution Result</h2>
<div id="result-container"></div>
<div id="error-message"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.3/sql-wasm.js"></script>
<script>
let db;
async function initDb() {
try {
const SQL = await initSqlJs({
locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.3/${file}`
});
db = new SQL.Database();
const setupSQL = `
CREATE TABLE products (id INT, name VARCHAR(255), category VARCHAR(255), price INT, release_date DATE);
INSERT INTO products (id, name, category, price, release_date) VALUES
(1, 'Fluffy Cushion', 'Interior', 3200, '2023-04-15'),
(2, 'Noise-Cancelling Earmuffs', 'Gadget', 7800, '2023-11-01'),
(3, 'Idea Spark Notebook', 'Stationery', 1200, '2022-08-20'),
(4, 'Glowing Keyboard', 'Gadget', 15000, '2023-06-30'),
(5, 'Ultimate Comfort Chair', 'Interior', 32000, '2022-11-10'),
(6, 'Smooth Ballpoint Pen', 'Stationery', 1200, '2023-09-01'),
(7, 'Creatorâs Mug Cup', 'Tableware', 2500, '2023-04-15');
`;
db.run(setupSQL);
executeQuery(); // Run initial SQL
} catch (e) {
document.getElementById('error-message').textContent = 'Failed to initialize the database: ' + e.message;
}
}
function executeQuery() {
const sqlInput = document.getElementById('sql-input').value;
const resultContainer = document.getElementById('result-container');
const errorMessage = document.getElementById('error-message');
resultContainer.innerHTML = '';
errorMessage.innerHTML = '';
try {
const results = db.exec(sqlInput);
if (results.length > 0) {
resultContainer.appendChild(createTable(results[0]));
} else {
resultContainer.innerHTML = '<p>Query executed successfully, but no result set was returned. (e.g., CREATE TABLE, INSERT)</p>';
}
} catch (e) {
errorMessage.textContent = 'Error: ' + e.message;
}
}
function createTable(result) {
const table = document.createElement('table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
const headerRow = document.createElement('tr');
result.columns.forEach(colName => {
const th = document.createElement('th');
th.textContent = colName;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
result.values.forEach(rowData => {
const tr = document.createElement('tr');
rowData.forEach(cellData => {
const td = document.createElement('td');
td.textContent = cellData;
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(thead);
table.appendChild(tbody);
return table;
}
initDb();
</script>
</body>
</html>
Supplement: SQL Dialect Differences by Database
The LIMIT ... OFFSET ... syntax we explained in this article is a standard format supported by many databases such as MySQL, PostgreSQL, and SQLite. However, some databases use different syntax (dialects), so weâll briefly introduce them here for reference.
For SQL Server
Microsoft SQL Server used to rely on the TOP clause in older versions, but in recent versions, the OFFSET ... FETCH ... clause is recommended.
-- Pagination in SQL Server (skip 3 rows and fetch the next 3)
SELECT * FROM products
ORDER BY id
OFFSET 3 ROWS
FETCH NEXT 3 ROWS ONLY;
For Oracle
Oracle Database also uses the OFFSET ... FETCH ... syntax, similar to SQL Server.
-- Pagination in Oracle (skip 3 rows and fetch the next 3)
SELECT * FROM products
ORDER BY id
OFFSET 3 ROWS
FETCH NEXT 3 ROWS ONLY;
As you can see, the syntax may vary depending on the database, but the underlying conceptâspecifying how many records to skip and how many to retrieveâis exactly the same.
Summary: Mastering LIMIT is Key to Mastering Data Display!
In this article, we explored the SQL LIMIT clause and its counterpart OFFSET, from the basics to advanced usage. Letâs recap the key takeaways:
LIMITrestricts the number of records retrieved.- Combining it with
ORDER BYis the classic pattern for fetching the "Top N" results. OFFSETshifts the starting point of retrieval (skips N rows from the top).- Using
LIMITtogether withOFFSETenables essential pagination for web development.
By retrieving only the necessary data in the necessary amount, the LIMIT clause helps maintain database performance and provides users with a smoother UI experience. Try out various scenarios in the demo environment and fully master its behavior!