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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Handling Missing Values with the ISNULL Function →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
How do you calculate OFFSET for pagination?
How do you skip rows in SQL Server?
Why can paginated results repeat or skip rows?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →