Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return just the first result of mysql Query

In one of my applications, I have to determine if 'foo_id' is present in the 'foo' column of a table 'foo_table'.

My requirements will be met as soon as I know there is one such 'foo_id' present. Now, my question is how to restrict this to the first match.

When I checked these queries against mySql EXPLAIN:

- select count(foo) from foo_table where foo=<foo_id>;
- select foo from foo_table where foo=<foo_id> limit 1;

In both of the cases, the number of rows was 58. Is there a way in mySql such that I can restrict the number of rows to 1 (the first match), such that rows are not touched unnecessarily (because I don't need that).

like image 683
TJ- Avatar asked Jan 03 '12 05:01

TJ-


People also ask

How do I get the first row of data in SQL?

The first () function is used to return the first row of any table.

How do I select the first 5 rows in MySQL?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I select the first row of a group in SQL?

The first way to find the first row of each group is by using a correlated subquery. In short, a correlated subquery is a type of subquery that is executed row by row. It uses the values from the outer query, that is, the values from the query it's nested into.


2 Answers

You can use EXISTS as such:

SELECT EXISTS(SELECT 1 FROM foo_table WHERE foo=<foo_id>).

The SELECT is ignored as EXISTS only checks the WHERE clause. As it is good practice to avoid using *, it is substituted by 1 here.

Here is the Documentation.

like image 30
Cameron S Avatar answered Oct 10 '22 02:10

Cameron S


explain plan will always show 58, because is number of records which match you criteria.

However LIMIT 1 is all you need.

like image 168
rkosegi Avatar answered Oct 10 '22 02:10

rkosegi