Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "LIMIT 1" recommended for query where WHERE condition is based on PK?

Tags:

I am querying a mySQL database to retrieve the data from 1 particular row. I'm using the table primary key as the WHERE constraint parameter.

E.g.

SELECT name FROM users WHERE userid = 4 

The userid column is the primary key of the table. Is it good practice to use LIMIT 1 on the end of that mySQL statement? Or are there any speed benefits?

like image 541
justinl Avatar asked Nov 21 '09 03:11

justinl


People also ask

Why do we use limit 1 in SQL?

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

Does limit optimize query?

The answer, in short, is yes. If you limit your result to 1, then even if you are "expecting" one result, the query will be faster because your database wont look through all your records. It will simply stop once it finds a record that matches your query.

Is there a limit to a where clause SQL?

The maximum number of clauses in a WHERE clause is 40. LONGVARBINARY and LONGVARCHAR columns can be compared to literals of up to 255 characters in length, but cannot be compared using parameters.

What is the use of limit clause with SELECT query?

The LIMIT clause can restrict the result set of the query to some maximum number of rows. If this clause specifies a value smaller than the number of qualifying rows, the query returns only a subset of the rows that satisfy the selection criteria.


1 Answers

I would call that a bad practice as when it comes to something like a userid it's generally unique and you won't have more than one. Therefore, having LIMIT 1 seems pretty contradictory and someone who comes to maintain your code later may have to second-guess your design.

Also, I don't think it has any speed benefit at all. You can check out mySQL's Explain for a simple tool to analyze a query.

Note, as mentioned in the comments. LIMIT # does have speed and general benefits in other cases, just not this one.

like image 175
Bartek Avatar answered Sep 28 '22 04:09

Bartek