tags:

views:

106

answers:

4

Right now using SQLite i write the below (I may move to either mysql or ms sql)

command.CommandText = "SELECT count(reset_key) user_data WHERE reset_key=@key;";

This works but is there a more optimized or cleaner way?

+4  A: 

That's about the cleanest, most optimized way there is. Make sure that there's an index on reset_key and it will be very, very fast.

Eric
That's right, how do you optimize something like that?
Cyril Gupta
Reading your comment on a post below i realized using an index column would be better. But, that doesnt matter if i must use a where? since i need to read the nonindex where column anyways? (if so then my code is fine).
acidzombie24
The `where` column is the one that needs to be indexed, since that's what the RDBMS is filtering on.
Eric
> "That's right, how do you optimize something like that? "If @reset_key is not a /unique/ key then the statement could be optimised by checking for the existence of a single row rather than counting all its occurrences.
APC
A: 

Try

  Select Case When Exists (Select * From user_Data
                           Where reset_key = @key)
              Then 1 Else 0 End
Charles Bretana
Do `select 1` instead of `select *`. No need to bring back the entirety of the column set when `exists` only cares about whether or not there's a row there. This would be slow if there's a `varchar(max)` field or something of that ilk. Also, this is really no faster than a `count` with an indexed column.
Eric
is that vb code? if your doing select * which returns all the columns then thats much worse.
acidzombie24
@Eric, Select * inside of an Exists does NOT bring back the entire row... It just checks to see if the row exists... exactly like Select 1 would do, but is the recommended syntax when using Exists().
Charles Bretana
A: 

SQLite has the support of LIMIT clause. That might help.

EDIT: I don't know the SQLite syntax. But in SQL sense, it would look like

Select 1 From user_Data Where reset_key = @key LIMIT 1
shahkalpesh
I can't see how LIMIT would help if there is only every going to be, at most, one row.
Dan Diplo
shahkalpesh
A: 
command.CommandText = "SELECT TOP 1 1 FROM user_data WHERE reset_key=@key"

if (commmand.ExecuteScalar() == null)
{
    //code for no matches here
}
CodeByMoonlight