Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving only a fixed number of rows in MySQL

Tags:

I am testing my database design under load and I need to retrieve only a fixed number of rows (5000)

I can specify a LIMIT to achieve this, however it seems that the query builds the result set of all rows that match and then returns only the number of rows specified in the limit. Is that how it is implemented?

Is there a for MySQL to read one row, read another one and basically stop when it retrieves the 5000th matching row?

like image 864
Sandman Avatar asked Apr 06 '12 19:04

Sandman


People also ask

How do I get only the specific number of rows in SQL?

The SQL SELECT TOP Clause The SELECT TOP clause is used to specify the number of records to return. The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.

How do I select only few rows in MySQL?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.

How do I LIMIT rows in MySQL?

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 which are offset and count. The value of both the parameters can be zero or positive integers.

Which clause in MySQL is used to display a fixed number of rows?

You can use LIMIT clause to select a set of rows.


1 Answers

MySQL is smart in that if you specify a LIMIT 5000 in your query, and it is possible to produce that result without generating the whole result set first, then it will not build the whole result.

For instance, the following query:

SELECT * FROM table ORDER BY column LIMIT 5000 

This query will need to scan the whole table unless there is an index on column, in which case it does the smart thing and uses the index to find the rows with the smallest column.

like image 119
Keith Randall Avatar answered Oct 19 '22 00:10

Keith Randall