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).
The first () function is used to return the first row of any table.
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.
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.
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.
explain plan will always show 58, because is number of records which match you criteria.
However LIMIT 1 is all you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With