Reputation: 835
Is there any way to make a select query that search a table for a given word and if it found then exit the query and do not continue counting?
for example I have a table (t1) have the values:
id tag tagdate
1 my 1-1-2012
2 name 1-1-2012
3 you 1-1-2012
4 foo 1-1-2012
5 make 1-1-2012
6 ir 1-1-2013
7 too 1-1-2013
.. .. ........
.. .. ........
.. .. ........
100000 foo 1-1-2013
for example i will make a query to make sure from the 'foo' word is exists or not and if exists just return 1 and stop continue query.
The query that i make now is a count to make sure from the word is exists on the table or not:
select count(tag) from t1 where tag = 'foo'
but that Sql statement search all the table for the word 'foo' and return its count on the table , and if we have 100,000 record in the table , the query will search on all the 100,000 records for 'foo' word. and that waste the time while we just want to know if 'foo' is exists on the table or not.
so is there any statement to search a table for a word and of the word found then its stop reading the table and return 1 or something like that?
Upvotes: 0
Views: 600
Reputation: 49089
I would do it this way:
SELECT EXISTS(SELECT NULL FROM t1 WHERE tag = 'foo')
This will return 0 (FALSE) if the tag foo doesn't exist, 1 (TRUE) otherwise. Using an index on the column tag
will avoid full table scan:
CREATE INDEX idx_tag ON t1 (tag);
Upvotes: 1
Reputation: 4957
You could try indexing to avoid full table scan.
http://dev.mysql.com/doc/refman/5.5/en/optimization-indexes.html
Upvotes: 0
Reputation: 17871
Maybe something like:
SELECT IFNULL(SIGN(id), 0) FROM t1 WHERE tag = 'foo'
LIMIT 1
Upvotes: 0