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
- What do you think about this tip? E-mail us at
- editor@searchDatabase.com with your feedback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBA's and developers? The best tips submitted will receive a cool prize--submit your tip today!
- Ask your technical SQL questions--or help out your peers by answering them--in our live discussion forums.
- Ask the Experts yourself: Our SQL gurus are waiting to answer your technical questions.
This was first published in June 2001