I m writing a query:
select * from table_name order by id limit 21
Until i use the limit is lesser or equal to 20 the rows getting scanned is equal to the exact fetching rows (for example if the limit is 10, than the scanned rows also 10 only). If the limit exceeds 20 the table getting scanned fully.
The only one index created for the primary key id only. Can anybody tell the reason for the full table scan in this case?
My table has 1099 rows.
Explain Result:
---------------------------------------------------------------------------
id|selecttype|table |type|possiblekeys|keys|key_len|ref |rows| Extra
---------------------------------------------------------------------------
1 | SIMPLE |tablen|ALL | null |null|null |null|1099|Usingfilesort
---------------------------------------------------------------------------
When a LIMIT clause is appended to a SELECT statement, it does not affect whether or not a full table scan is performed. However, the LIMIT clause affects the number of results returned for the query, but not how many rows are scanned for a table.
What are some of the ways to avoid a full-table scan? Indexes: Ensure that indexes exist on the key value and that the index has been analyzed with dbms_stats. Use_nl hint: You can direct that the optimizer use a nested loops join (which requires indexes). index hint: You can specify the indexes that you want to use.
In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers.
Create useful indexes Indexes are useful when a query contains a WHERE clause. Without a WHERE clause, Derby is supposed to return all the data in the table, and so a table scan is the correct (if not desirable) behavior. (More about that in Prevent the user from issuing expensive queries.)
In general case, to return rows for a LIMIT M, N
MySQL will have to scan M+N rows of the result without LIMIT
, and skip the first M-1 of them, hence full table scan.
The first 20 rows in your case seem to fit into a single page, and since you order by the primary key, MySQL probably understands that it won't need to make full table scan.
Another thing one should know, MySQL usually does not use any indexes for queries like SELECT * FROM T ORDER BY something
, indexes are usually used when there is a condition, or if all the data can be fetched from the index directly (covering indexes).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With