Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limited SQL query returns all rows instead of one

I tried the SQL code:

explain SELECT * FROM myTable LIMIT 1

As a result I got:

id select_type table   type possible_keys key  key_len ref  **rows**
1  SIMPLE      myTable ALL  NULL          NULL NULL    NULL **32117**

Do you know why the query would run though all rows instead of simply picking the first row? What can I change within the query (or in my table) to reduce the line amount for a similar result?

like image 871
Peter Frey Avatar asked Nov 14 '12 18:11

Peter Frey


People also ask

How do I limit the number of rows returned in SQL?

If you don't need to omit any rows, you can use SQL Server's TOP clause to limit the rows returned. It is placed immediately after SELECT. The TOP keyword is followed by integer indicating the number of rows to return. In our example, we ordered by price and then limited the returned rows to 3.

What SQL clause is used to restrict the rows returned by a query?

LIMIT clause in the SQL is used to restrict the number of records. In simple words, it is used to set an upper limit on the number of tuples returned for any given query.

What does limit 1 do in SQL?

The LIMIT clause is used to set an upper limit on the number of tuples returned by SQL. It is important to note that this clause is not supported by all SQL versions. The LIMIT clause can also be specified using the SQL 2008 OFFSET/FETCH FIRST clauses.

Which clause limits the returned data to a row count?

In the SELECT argument, the LIMIT clause is used to LIMIT the number of rows to be returned.


1 Answers

The rows count shown is only an estimate of the number of rows to examine. It is not always equal to the actual number of rows examined when you run the query.

In particular:

LIMIT is not taken into account while estimating number of rows Even if you have LIMIT which restricts how many rows will be examined MySQL will still print full number.

Source

When the query actually runs only one row will be examined.

like image 110
Mark Byers Avatar answered Sep 25 '22 22:09

Mark Byers