Limiting the Scope: LIMIT and OFFSET
The Saturday Performance Check
As the startup grew, our tables became massive. I was no longer dealing with hundreds of rows, but hundreds of thousands. I noticed that when I ran samples, my screen would hang for a few seconds.
I didn't need to see *everyone* just to check if my query was working. I needed a way to pull a sample size.
The Quest: The Speed of Snippets
In professional data analysis, you often want to "Peek" at the data or create "Top N" lists (Top 5 customers, Top 10 sales). To do this without wasting the database's time, we use `LIMIT`.
The Implementation: Setting the Boundary
`LIMIT` tells the database: "Stop after you find X number of rows."
-- Just show me the top 5 most expensive products
SELECT product_name, price
FROM products
ORDER BY price DESC
LIMIT 5;
Pagination with OFFSET
What if you want the *second* five items? (Like the "Next Page" in a search engine). We use `OFFSET`.
-- Skip the first 5, then take the next 5
SELECT product_name, price
FROM products
ORDER BY price DESC
LIMIT 5 OFFSET 5;
The "Oops" Moment
I once tried to use `LIMIT` without an `ORDER BY`. The results were "Random."
**Pro Tip**: `LIMIT` is almost useless without `ORDER BY`. Without instructions on how to sort, you are just getting the first five rows the database happens to find in its memory.
The Victory
My queries became lightning-fast. I could test my logic on 5 rows, and once I was sure it worked, I could remove the `LIMIT` and run it on 50,000. It's the difference between a prototype and an engine.
Your Task for Today
Take your sorted query from yesterday and add `LIMIT 10`. Then, change it to `LIMIT 10 OFFSET 10` to see the "Second Page" of your data.
*Day 7: The Art of Naming—Aliases (AS).*