decode(text_to_compare,value_to_compare,result_if_true,result_if_false);
Let's see decode in action to firm up everyone's understanding.
- select decode('test','test','They are equal!','Um.. not so much.') from dual;
- DECODE('TEST','TEST','THEY ARE EQUAL!','UM..NOT SO MUCH.')
- ------------------------------------------------------
- They are equal!
1 rows selected
As you can see, when 'test' equals 'test' then we get 'They are equal!'. Okay, so that's pretty boring on a good day. Let's dig in a more complex example. I have a table called decode_test for obvious reasons that contains information about products that have been sold by yours truly.
- select name, product_id, decode(product_id,
- 1,'Stereo System',
- 2,'Blu-Ray DVD Player',
- 3,'Brick of Gold',
- 'Other stuff laying around store.') from decode_test;
- NAME PRODUCT_ID PRODUCT_NAME
- -------------------- ---------------------- --------------------------------
- Nicholas 1 Stereo System
- Nicholas 3 Brick of Gold
- Nicholas 2 Blu-Ray DVD Player
- Nicholas 1 Stereo System
- 4 rows selected
Okay so what happened here? Basically in my test, each product_id represented some text I wanted to display in there query. You'll notice decode can take multiple value pairs to test against the input text.
So I'll admit the previous example won't win any "Example of the Year" awards. So here is a more practical use of decode that involves dates and conditional summation.
- select name,
- sum(decode(to_char(date_sold,'MMYYYY'),current_month,amount_sold,null)) as sales_month_to_date,
- sum(decode(to_char(date_sold,'YYYY'),current_year,amount_sold,null)) as sales_year_to_date
- from decode_test,
- (select to_char(sysdate,'MMYYYY') as current_month,
- to_char(sysdate,'YYYY') as current_year from dual) d
- group by name;
- NAME SALES_MONTH_TO_DATE SALES_YEAR_TO_DATE
- -------------------- ---------------------- ----------------------
- Nicholas 67.5 132.5
- 1 rows selected
Well, well, that was halfway slick. In the previous example, I needed to sum only the sales for the current month and for year to date. Decode helped me to sum the amount_sold, when it was appropriate.