Using LIMIT when querying a single row

mysql_logo

Sometimes you know you are only looking for one row when you are querying your tables. It may be that you are fetching a unique record or checking the existence of any number of records that satisfy your WHERE clause.

Adding LIMIT 1 to your query can increase performance in this situation; – the database engine will stop scanning for records after it finds just one, instead of going through the whole table or index.

For example:
$record = mysql_query("SELECT username FROM user WHERE country = 'UK'");
if (mysql_num_rows($record) > 0) {
// ...
}

Can become:
$record = mysql_query("SELECT username FROM user WHERE country = 'UK' LIMIT 1");
if (mysql_num_rows($record) > 0) {
// ...
}

Leave a Comment

Your email address will not be published. Required fields are marked *