Returning a unique value that may or may not exist

This tip shows you how to return a value from an unknown unique record.

Suppose you want to return a value from a unique record in the database, but the record's existence is not known

to you. The simple way is to do SELECT COUNT, and if the count > 0 then select the value.

I suggest another way:

Suppose, for example, you want to get the salary of employee code 100 in table EMP. Employee 100 may exist or may not exist in the database. In case he or she does not exist, -1 should be returned.

  SELECT NVL(MIN(SALARY),-1)
  FROM EMP 
  WHERE EMP_CODE = 100

That will do it. If EMP exists, the value will be returned. If not, MIN function will give NULL that will be converted to -1 by the NVL. MIN does not cost because it's used on one row only.

.

For More Information


This was first published in June 2001

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close