devxlogo

Use Decode Function for Oracle Queries

Use Decode Function for Oracle Queries

Decode is a very useful and handy function for Oracle queries. Itreplaces the complex If-Then-Else logic, which is used to display different things based on different values in a column.

Consider the following example in which the Viewable column can have values of 1,2, and 3:

 SELECT FirstName, ViewableFROM   employee;Results:FIRSTNAME		Viewable===========================John			1Tim			2Julie			2Stacy			1Rahul			3Leena			4Amy			1Bill			3Teri			3

Now, we can use Decode to display different things in a report based on the values inViewable.

 SELECT Firstname,      Decode(Viewable, 1,'VISIBLE', 2,'INVISIBLE', 
3,'UNKNOWN', 'OTHER')FROM employee;Results:FIRSTNAME Viewable===========================John VISIBLETim INVISIBLEJulie INVISIBLEStacy VISIBLERahul UNKNOWNLeena OTHERAmy VISIBLEBill UNKNOWNTeri UNKNOWN

Decode checks the column values and interprets the provided valuesin pairs. This is how it works:

 Switch viewable:Case 1:    Result = VISIBLECase 2:    Result = INVISIBLECase 3:    Result = UNKNOWNDefault:    Result = OTHEREnd CaseOR====================If Viewable = 1 Then    Result = VISIBLEElsif Viewable = 2 Then    Result = INVISIBLEElsif Viewable = 3 Then    Result = UNKNOWNElse    Result = OTHEREnd If

One can use Decode in Updates as well. For example, instead of writing 50 different updates to change state names, we can do it in one Update using Decode as follows:

 Update employeeset    homestate = decode(homestate,                         'AL', 'Alabama',                        'AK', 'Alaska',                        'AS', 'American Samoa',                        'AZ', 'Arizona',				. . . . . . . .                        . . . . . . . .                         'WA', 'Washington',                        'WV', 'West Virginia',                        'WI', 'Wisconsin',                        'WY', 'Wyoming' , homestate) where homecountry = 'UNITED STATES'

This will replace state abbreviations with state names. And it leaves theabbreviations alone in case it doesn’t match any of the values, such as AL, AK, etc.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist