Controlling Result Size: Limiting Query Output, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 5.2 Free with a free account

Controlling Result Size: Limiting Query Output

Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.2 · lesson 27 of 768 min · free with a free account

← Adding Records with the INSERT StatementNext lesson: Handling Missing Values with the ISNULL Function →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Using LIMIT, OFFSET, TOP, and FETCH to return small, ordered results.

  • Write top-N queries with ORDER BY and LIMIT in MySQL or TOP in SQL Server
  • Calculate the OFFSET for a requested page from page number and page size
  • Compare MySQL LIMIT forms with SQL Server OFFSET-FETCH syntax
  • Explain why tie-breakers and keyset pagination make paging more reliable

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,036 words). Read along, or search it.

Opening Question

Downloading the Whole Catalog for a Shortlist

Sofia Alvarez handles sales at Lantern Books. She wants a small price shortlist, but the application downloads the entire catalog before discarding almost everything. Can the database send just the useful rows? Yes, but first Sofia must define what makes a row belong at the front. A row limit caps the returned result. A top list and a browsing page both need that cap, together with a deliberate order.

Sort Order

Unsorted Results Have No Guaranteed Order

Our disposable catalog uses the same eight bookstore products. Categories are an illustrative extension; the product identifiers, prices, and stock retain their course values. A table has no guaranteed presentation order. An index, a different plan, or changed data can alter an unsorted result. Price descending places expensive products first. Ascending, the default direction, places cheaper products first; neither direction changes the stored records. When prices tie, add a unique identifier as the final sort key. That resolves the tie, without pretending that changing data will stay still. These examples run in SQLite, whose limit and offset form also appears in MySQL. SQL Server uses different limiting words.

Top-N Query

Three Most Expensive Products With LIMIT

Ask for the three most expensive products. Select chooses the displayed columns, and order by defines the ranking before limit selects a window. Limit three means at most three returned rows. It does not promise three when fewer rows qualify, nor three different price values. Sorting may still require substantial work before any row can be returned. The reliable benefit is a smaller result to transmit and display. Run the ordered query. Its descending direction puts the highest price at the beginning, while the identifier resolves any equal prices. Biology Guide, Database Basics, and Statistics Workbook form this shortlist. Reverse the price direction to ask for the cheapest items instead.

Offset

Skipping Rows With OFFSET

A second window skips the first three sorted rows. Offset counts skipped rows, while limit caps how many following rows come back. Offset zero skips nothing. Offset three starts after three rows; it does not mean start at a row whose identifier equals three. MySQL also accepts a comma form with offset first and count second. Writing the word offset makes the two roles easier to read. Run this window over the same ordering. This changes which part of the result is visible, without deleting any product. Reading Lamp, World History, and Pen Set occupy the following positions. A past-end offset returns an empty result rather than a special missing-page error.

MySQL Rules

LIMIT Count OFFSET Versus the Comma Form

Read these non-run MySQL fragments carefully. Limit five offset three means skip three, then return at most five. The comma form writes those numbers the other way around. Confusing the two forms silently asks for a different window. MySQL expects nonnegative integer arguments or supported parameter forms. Calculate page arithmetic before supplying a literal limit; arbitrary arithmetic is not accepted there. A zero limit returns no rows, and clients can still inspect result metadata. A small positive limit also works when the relation contains fewer rows. An empty page is ordinary data, not proof that the database failed. Let the interface distinguish an empty result from a query error.

SQL Server Syntax

TOP, WITH TIES, and OFFSET-FETCH

SQL Server places top after select. Parentheses around its count are the recommended form; these listings are never sent to SQLite. Top percent requests a share of qualifying rows. A fractional row count rounds up; a share of eight products can differ from the same numeric fixed count. With ties includes extra rows equal on the full ordering key at the boundary. Adding a unique identifier there removes ties, so choose the intended ranking. For skipping, SQL Server attaches offset and fetch to order by. This form arrived in SQL Server twenty twelve, and order by is required. Fetch needs offset, even when nothing is skipped. Row and rows are synonyms, as are first and next; do not combine top with offset-fetch in one query scope.

Pagination

Page Number to Offset Arithmetic

Pagination divides a sorted result into windows. The page size is rows per page; the page number identifies which window the viewer requests. Compute the offset as page number minus one, multiplied by page size. Page two at three rows per page skips three rows. Count matching rows to estimate page count, then round the quotient upward. Eight rows at size three need three pages; the final page is shorter.

Keyset Pagination

Continuing After the Last Seen Key

A deep offset can be expensive, because the engine may visit many skipped entries. Sequential browsing can instead remember the last ordering key. Here the previous page ended at identifier fourteen. The filter asks for later keys, and the same key defines the order. Run the next-page request. An appropriate index can help find this starting point, instead of repeatedly counting a large prefix. The result starts after that saved key. This keyset pattern suits forward navigation; jumping directly to an arbitrary page usually requires more work.

Consistency

Changing Data Can Shift Pages

A unique tie-breaker solves ambiguous ties. It does not prevent products being inserted, removed, or repriced between two page requests. With offsets, a changed earlier row can shift later windows, repeating one product or hiding another. Stable snapshots or suitable keyset designs address different consistency needs. For a composite price order, remember the price and identifier together. An identifier-only filter would not describe the same boundary in that ranking.

Quick Check

Third Page at Two Rows per Page

Sofia changes browsing to identifier order, ascending, with two products per page. This new query requests the third page of the unchanged catalog. Which pair of identifiers will it return? Pause, and predict.

Answer

Offset Counts Rows, Not Key Values

The answer is fifteen and sixteen. Page three skips two complete pages of two records, leaving the fifth and sixth identifiers in the ordered catalog. Thirteen and fourteen belong to the preceding window. Seventeen and eighteen belong to the following window, so neither describes the requested offset. The result confirms the arithmetic. Offset is a count of earlier result rows, rather than a value to match in the key column.

Key Takeaways

Sort First, Then Cap the Window

Sofia can now request a shortlist or one page directly. She defines the sort first, adds a suitable tie-breaker, and caps the returned window. Use the dialect's limiting form, and calculate the skipped prefix from page size and number. Treat a short or empty page as a normal result. Choose a paging strategy for the application's navigation and consistency needs. A small returned result is useful, but the execution plan still determines the work.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Controlling Result Size: Limiting Query Output

What is the difference between LIMIT and TOP in SQL?
Both cap how many rows a query returns, but they belong to different dialects and sit in different places. MySQL and SQLite put LIMIT at the end, as in SELECT name, price FROM products ORDER BY price DESC LIMIT 3. SQL Server puts TOP right after SELECT, as in SELECT TOP (3) name, price FROM products ORDER BY price DESC. Without ORDER BY, neither promises which rows come back.
How do you calculate OFFSET for pagination?
OFFSET equals (page - 1) * page_size, the number of rows on all earlier pages. For page three with two rows per page, the offset is 4, so the query ends with ORDER BY product_id LIMIT 2 OFFSET 4. The offset counts rows to skip, not key values. To find how many pages exist, divide the row count by the page size and round up, so 8 rows at 3 per page need 3 pages.
How do you skip rows in SQL Server?
SQL Server skips rows with OFFSET and FETCH after ORDER BY, as in ORDER BY price DESC OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY, available since SQL Server 2012. The ORDER BY clause is required, and FETCH cannot appear without OFFSET, so the first page uses OFFSET 0 ROWS. ROW and ROWS are interchangeable, as are FIRST and NEXT. TOP cannot be combined with OFFSET-FETCH in the same query expression.
Why can paginated results repeat or skip rows?
Pages repeat or skip rows when the sort order has ties or the data changes between requests. If several products share a price, ORDER BY price alone lets tied rows swap places, so add a unique tie-breaker such as product_id. Inserts, deletes, or price changes between page requests can also shift later OFFSET windows. Keyset pagination, which continues after the last seen key, reduces this drift.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →