Is this the best(most efficient) way to check if a row exists in a table?
SELECT EXISTS(SELECT 1 FROM myTbl WHERE u_tag="tag");
// Table is...
// CREATE TABLE myTbl(id INT PRIMARY KEY, u_tag TEXT);
Also what is the return value for this, is it false(bool) or 0(int) or NULL?
Though the documentation does not imply it, apparently the primary sqlite dev (Richard Hipp) has confirmed in the mailing list that
EXISTS
short circuits for you.So the query you proposed will be the most efficient:
If you were nervous about portability, you could add a limit. I suspect most DBs will offer you the same short circuit however.
Selecting 1 is the accepted practice if you don't need something from the record, though what you select shouldn't really matter either way.
Put an index on your tag field. If you do not, a query for a non-existent tag will do a full table scan.
EXISTS
states that it will return 1 or 0, not null.Again, quoting from the documentation:
As to whether or not using
EXISTS
is more efficient than, say, usingcount(*)
, that may depend on the size of the table and whether the table has an index. Try an EXPLAIN on both queries to benchmark (or just time each of them).