Sunday 10 March 2013

PLSQL - Decoding time

 PL SQL Decode Function

Some of my friends told me to write something about famous decode :)
So here it goes ....

What is decode?

Decode is implemented function that has the functionality of an IF THEN ELSE statement.
But there is one major difference between implementing these two functionality. DECODE can only work in select statement.You need to have in mind that DECODE is supported only in SQL Context so you don't really working with PL code. More flexible than decode is case statement....
The syntax for the decode function is: decode( expression , search , result [, search , result]... [, default] )
expression is the value to compare.

search is the value that is compared against expression.

result is the value returned, if expression is equal to search.

default is optional. If no matches are found, the decode will return default. If default is omitted, then the decode statement will return null (if no matches are found).


So something to decode now....
 let's create some table


CREATE
   TABLE company
   (
      id            NUMBER(32) NOT NULL,
      company_id    NUMBER(8),
      owner_name    VARCHAR2(20 byte),
      street_adress VARCHAR2(20 byte)
   );

insert some data in it

   insert into company values (1,10001,'Nerad Kovacevic','Neradna BB');
   insert into company values (2,10003,'Vedran Rudjic','Shvalerska 22');
   insert into company values (3,10006,'Ljuban Draga','Vlak u snijegu bb');

select * from company;

you will get 








let's say 10001 is IBM company's id, 10003 is Microsoft and 10006 is TrainStation Co :)

and now we want to display some writings instead of company id's so we decode it
Pseudo-code; if i found id by the number of 10001 i will write 'IBM' if that number is 10003 i will write 'Microsoft' if that number is 10006 i will write 'TrainStation Co' if i don't find (ELSE) number that i have in my decode function i will write 'Nameless'
select decode(company_id,10001,'IBM',10003,'Microsoft',10006,'Trainstation Co','Nameless') as company_name , owner_name, street_adress from company;

after running statement we get;








Lets insert one more row...


insert into company values (3,10009,'Unknown','UNKNOWN bb'); 

and run our statement again and for every undefined id we will get Nameless in company name column...

select decode(company_id,10001,'IBM',10003,'Microsoft',10006,'Trainstation Co','Nameless') as company_name , owner_name, street_adress from company;








So that's about it...

Simple decode function....

Anyway you can find it useful in many occasions and it's use is quite simple and in many situations very grateful...

so one last example

 select decode((select id from company where id = 1 ),1,'IBM',2,'Microsoft',3,'Trainstation Co','Nameless') as company_name , owner_name, street_adress from company where rownum < 2;






Happy decoding :D

0 comments:

Post a Comment