|
Custom Search
| |
|
Using LIMIT Clause to Constrain the Number of Rows Retrieved If a table contains one million rows and you only want to retrieve data from row 1 to row 100, you can use the LIMIT clause. The LIMIT clause is used to constrain the number of rows returned by the SELECT statement. Read Prerequisites for this tutorial and practices if you haven't done so. Consider the following facts when using LIMIT clause in a SELECT statement:
Most of the queries in the tutorials need Northwind MySQL database, you can download the database script on this page. Practice #1: Use two numeric arguments in LIMIT clause /*
Query result set - 10 rows returned: Practice #2: Use one argument in LIMIT clause /*
Query result set - 15 rows returned: Practice #3: Using LIMIT with OFFSET OFFSET indicates which row we want the data to be retrieved from. The first query below uses OFFSET with LIMIT. It retrieves 10 records starting from the 6th row in table products. LIMIT 10 OFFSET 5 is equivalent to LIMIT 5,10 in the second query. You need to swap the two numbers if you use the shorter version without keyword OFFSET.
-- Retrieves 10 records starting from the 6th row in products table
SELECT ProductID, ProductName FROM products ORDER BY ProductID LIMIT 10 OFFSET 5; -- Equivalent query SELECT ProductID, ProductName FROM products ORDER BY ProductID LIMIT 5,10;
Query result set - 10 rows returned: Practice #4: Using LIMIT 0 to validate a query rather than execute it /* LIMIT 0 is very useful when you need to validate a complex query. Sometimes when you expect a query to return a large number of rows but you are not sure if the SQL syntax is correct, you can use LIMIT 0 to validate the query. This reduces server load.
Query result set - 0 rows returned: Other tutorials in this category 1. The Basic SELECT Statement |
Copyright © 2024 GeeksEngine.com. All Rights Reserved. This website is hosted by HostGator. No portion may be reproduced without my written permission. Software and hardware names mentioned on this site are registered trademarks of their respective companies. Should any right be infringed, it is totally unintentional. Drop me an email and I will promptly and gladly rectify it. |
Home | Feedback | Terms of Use | Privacy Policy |