Question

Is this the safest/optimal code for a simple "does the record exist" question:

. . . // "oc" is an OracleConnection component
const string sql = "SELECT COUNT(*) FROM CONGRESS WHERE IQ > WEIGHT"; //Most politicians have more pounds than sense
try {
    using (OracleCommand ocmd = new OracleCommand(sql, oc)) {
        return Convert.ToInt32(ocmd.ExecuteScalar()) > 0;
    }
. . . // the rest elided to spare the vertical scroll-bar bearings

?

Was it helpful?

Solution

Something like

SELECT 1
  FROM dual
 WHERE EXISTS( SELECT 1
                 FROM congress
                WHERE iq > weight )

is probably the safest option since that allows Oracle to stop executing the query as soon as one matching row is found rather than scanning the entire table to get an accurate count. Something like

SELECT COUNT(*) 
  FROM congress
 WHERE iq > weight
   AND rownum <= 1

should do the same thing as well. In my mind, the first query is more expressive of your intent but it's also a bit more verbose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top