Friday, December 9, 2011

Oracle Interview Questions Part 1: SQL

Q: What is the difference between delete and truncate?
Ans:
1. Delete can be rolled back before commiting the transaction whereas a truncate cannot be rolled back
2. Delete is a DML whereas Truncate is DDL
3. Truncate deletes the entire data at once whereas delete does it row by row.
4. Truncate is faster and performance benefit when compated to delete, if the requirement is to flush the table completely.

Q: What is the syntax of DECODE function and what is the use?
Ans: It has the same functionality IF-THEN-ELSE statement.
syntax: decode(expression,search[,result,search,result..][,default])

Example:
select decode (department, 1, 'Finance',2,'Accounts', 'Miscellaneous') from dual;

Q: What does COALESE function does?
Ans:
COALESCE function goes through the given list of values/expressions and returns the first non null expression. If all the values/expressions are null then it returns null. COALESCE is similar to IF-THEN-ELSE statement.

syntax: coalesce( expr1, expr2, ... expr_n )
SELECT coalesce( firstname, middlename, lastname) result
FROM employees;

Its equivalent IF-THEN-ELSE is as below.

IF firstname is not null
THEN
result:=firstname;
ELSIF middlename is not null
THEN
result:=midddlename;
ELSIF lastname is not null
THEN
result:=lastname
ELSE
result:=null;
end if;

Q: A given column has values with NULL data. On sorting the column in ascending order, where does the null value comes? First or Last?

Ans: Last

Q: What is the default sort order in Oracle?

Ans: ascending


Q: Provided a list of numbers or characters or dates. What function helps you to retrieve the highes value from the list?
Ans: greatest(x,y,..)
and for the least it is least(x,y,..)

Q: The column firstname is of datatype varchar2 which has null values as well. What is the output of below function for a null value?
NVL(firstname,0)
Ans: NVL returns the passed value if the expression is null else returns the erpression.
Here the function fails as the column is of datatype varchar2 and the specified value is of type number. Hence it fails.

For NVL to work, the data type of both column and passing value should be same.

Q: How NVL2 works?
Ans: syntax: NVL2(X,Y,Z)
NVL2 returns Y if X is not null, else returns Z

Q: What is the syntax for NULLIF?
Ans: NULLIF(x,y)
function returns NULL if x=y else returns X

Q: Write an SQL query to fetch all the managers from an employee table whose JOB_ID ends with either '_MAN' or '_MGR'

Ans:
SELECT FIRST_NAME, LAST_NAME, JOB_ID
FROM EMPLOYEES
WHERE REGEXP_LIKE(JOB_ID, '(_m[an|gr])', 'i');

[parameter i indicates case-insensitive]

Q: Select every employee whose last name has a double vowel
(two adjacent occurrences of the same vowel).
Ans:
SELECT FIRST_NAME, LAST_NAME
FROM EMPLOYEES
WHERE REGEXP_LIKE(LAST_NAME, '([AEIOU])\1', 'i');

Q: Exmaple for using REGEXP_REPLACE

Ans:
SELECT PHONE_NUMBER "Old Format",
REGEXP_REPLACE(PHONE_NUMBER,
'([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})',
'(\1) \2-\3') "New Format"
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 90;



Old Format                                              New Format
-----------------------------------------------------------------
515.123.4567 (515) 123-4567
515.123.4568 (515) 123-4568
515.123.4569 (515) 123-4569

The search pattern has three regular expressions, each of which is enclosed in parentheses. The metacharacter [[:digit:]] represents a digit, the metacharacter {n} specifies n occurrences, and the metacharacter \ is an escape character. The character immediately after an escape character is interpreted as a literal. Without the escape character, the metacharacter . represents any character. The replace string uses \1, \2, and \3 to represent the first, second, and third regular expressions in the search pattern, respectively. (In the replace string, \ is not an escape character.)


Q: Example to extract Street number including hyphen from the given street address.
Ans:
select street_address address, REGEXP_SUBSTR(street_address,'[[:digit:]-]+') "Number" from locations

Address                                   Number
-----------------------------------------------
2007              Zagora St 2007
2004              Charade Rd 2004
147                Spadina Ave 147
6092              Boxwood St 6092
40-5-12         Laogianggen 40-5-12



Q: Can we use a oracle keyword as alias in any select statement?
select 1 number from dual;

ORA-00923: FROM keyword not found where expected
00923. 00000 -  "FROM keyword not found where expected"
*Cause:   
*Action:
Error at Line: 1 Column: 9

solution: Use the keyword in double quotes

select 1 "number" from dual;

Output:
number
---------
1

Q: Example to count number of spaces in a street address
Ans:

Q: What is the result of below query? Why?
select 10000 + null from dual;

Ans: null. In oracle any scalar operation with null always results in null.

Wednesday, December 7, 2011

How to type in French charcters from your keyboard

Search for French Characters in your key board ends here!!


Fortunately or Unfortunately I came across a requirement to type in French characters in my system. I started searching for those odd characters in my key board and the end result was failure. I couldn't find it at all..

Before explaining how to type in French Characters let us have a basic understanding about French alphabets.

French alphabet consist of 26 letters, lowercase and uppercase, with five diacritics and two orthographic ligatures. The latter part, diacritics and ligatures, is what we are inerested about and need to know how we type it in.

Below listed down are the Diacritics and Ligatures:

Àà, Ââ, Ææ
Çç
Éé, Èè, Êê, Ëë
Îî, Ïï
Ôô, Œœ
Ùù, Ûû, Üü
Ÿÿ

Getting confused with the special characteres?
Lets us make it much more simple. For this let us look into Diacritics and Ligatures seperately.

Diacritics:
All the special characters that you have seen in the above table on top of each characters is called Diacritic Marks. The possible diacritic marks are the acute(´), grave(`), and cicumflex (^) accents, the diaresis  (¨)  and the cedilla ( ¸ ).

Let us not go much deep into how these are combined with our alphabets and how it is pronounced.

Ligatures:
There are two ligatures œ and æ which are treated like the sequences oe and ae.

Now, I hope you got a basic idea about the French characters and so moving to check on how to type in those characters from our keyboard.

The idea of typing in French characters works out with alt key and some 3 or 4 digit numbers. What you have to do is to press down the alt key and enter the 3 or 4 digit number and on releasing the alt key, your required French character will appear.

Below are the list of combinations and now its time for you to test it.
Grave AccentAccute AccentCircumflexTrémaLigatureCedilla
aALT + 133 (à)NAALT + 131 (â) ALT + 132 (ä)ALT + 145 (æ)NA
AALT + 0192 (À)NAALT + 0194 (Â)ALT + 142 (Ä)ALT + 146 (Æ)NA
eALT + 138 (è)ALT + 130 (é)ALT + 136 (ê)ALT + 137 (ë)NANA
EALT + 0200 (È)ALT + 144 (É)ALT + 0202 (Ê)ALT + 0203 (Ë)NANA
iNANAALT + 140 (î)ALT + 139 (ï)NANA
INANAALT + 0206 (Î)ALT + 0207 (Ï)NANA
oNANAALT + 147 (ô)NAALT + 0156 (œ)NA
ONANAALT + 0212 (Ô)NAALT + 0140 (Œ)NA
uALT + 151 (ù)NAALT + 150 (û)ALT + 129 (ü)NANA
UALT + 0217 (Ù)NAALT + 0219 (Û)ALT + 154 (Ü)NANA
CNANANANANAALT + 135 (ç)
CNANANANANAALT + 128 (Ç)


Found it useful? Please leave a comment.

Monday, December 5, 2011

Replace funtion in Javascript

Replace function description:
The replace function, replace(), looks for a substring in the given string and replaces that with new value provided.

The syntax for using this is:

string.replace(substring,newstring)

Example:
Assume variable string has values assigned as string ="AtoZ on Tech"
Using replace functin on this, provide the substring and newstring to replace
i.e
<script type="text/javascript">
var string="AtoZ on Tech";
string=string.replace("to","2");
document.write(string);
</script>


Output:
A2Z on Tech

Done a slight modification in susbstring. Will this work?

<script type="text/javascript">
var string="AtoZ on Tech";
string=string.replace(/to/,"2");
document.write(string);
</script>


Yes, this works same exactly as the above code.

Will the below code work?
<script type="text/javascript">
var string="AtoZ on Tech";
string=string.replace("To","2");
document.write(string);
</script>


No, as here "T" is in uppercase. So, how can we have a case-insensitive search and replace?
<script type="text/javascript">
var string="AtoZ on Tech";
string=string.replace(/To/i,"2");
document.write(string);
</script>


Output: A2Z on Tech

Now, let me extend our string variable. as below.
<script type="text/javascript">
var string="AtoZ on Tech";
string= string + " is a blogsite discussing all about technology from A to Z";
string=string.replace(/To/i,"2");
document.write(string);
</script>


Output:A2Z on Tech is a blogsite discussing all about technology from A to Z
The second "A to Z" is as it is. Here only the first occurance is replaced. How to replace all the occurences of search string?

Then you should give the option for global represented by "g.

<script type="text/javascript">
var string="AtoZ on Tech";
string= string + " is a blogsite discussing all about technology from A to Z";
string=string.replace(/To/ig,"2");
document.write(string);
</script>


Now you know that we have used "i" for case-insensitive matching and "g" for global matching. These are called modifiers. Modifiers will specify what kind of search we have to do. There is one more modifier used in javascript, ie "m" for multiline matching. This we will be discussin in our later blogs.


Ok. So far is fine. What if you dont have a specific substring and you have only a pattern to be replaced?

Then you have to go for Regular Expression.

What is Regular Expression?
Regular Expression gives a pattern of characters like a-z for chars, 0-9 for int and can have some special character pattern as well.

Using regular expression we search for any pattern defined in the regular expression(RegExp) and replace it with the required string/value.

<script type="text/javascript">
var string="A2Z on Tech";
string=string.replace(/[^a-z,0-9]/ig,"-");
document.write(string);
</script>


The above code looks for a pattern match (any character other than a-z, A-Z and number 0-9) and is replaced by -. (This is one which we generally use to generate SEO friendly URL)

Friday, December 2, 2011

Find the number of occurence of a character in a given string in Oracle

Scenario: Need to find out the number of occurrence of a particular character in the given string.

Example: Find number of "e"s in the given string ("Oracle is an interesting thing to learn.")

Solution:
select length('Oracle is an interesting thing to learn') - length(replace('Oracle is an interesting thing to learn','e',''))
from dual;
4

Explained:
59-55 = 4, Hence four occurrence.

Another one Use Case:
Get number of comma separated values in a given column where the values are 100,123,124,145.

Use above method to find number of occurrence of character , (comma) in the givens string and add one to that gives you the number of comma separated values.


In Oracle 11g we have new function to save our time and shorten our code length.

REGEXP_COUNT

select regexp_count('EXPERIENCE','E') FROM DUAL;

This will give you the result 4.

Thursday, December 1, 2011

Understanding UNIX hierarchichal file system

In UNIX the fundamental basic principle is that anything that is not a folder is file, whether it be a normal file, I/O connections anything.

Using calculator in UNIX

UNIX provides both INFIX and POSTFIX calculators.

INFIX is when the operations are embedded within the operators
12*2

POSTFIX is when the operators are listed down and then followed by operations.
12 2 *

So, now to use infix calculator type the command "bc"
bash-3.00$ bc
Nothing happend. Now type in what you need to calculate and the system gives you output
1*2
2
1*2+3
5
2+3*2
8

Ok, now how to get out of this? Its simple. "quit"
.
.
2+3*2
8
quit
bash-3.00$

Various powerful options with bc command:

Find square root?

bash-3.00$ bc
sqrt(16)
4
similarly use below:


Postfix calculator:

user command "dc"

bash-3.00$ dc
2
3
*
p
6
2 3 *
p
6
2 3 * 4 +
p
10
Use "p" to print the result of your calculation.
sqrt(n) Square root of n
% Remainder
^ To the power of (3^5 is 3 to the power of 5)
s(n) Sine(n)
c(n) Cosine(n)
e(n) Exponential(n)
l(n) Log(n)

How to find the date and time in an UNIX system

What I would like to know is the current date and time, so just type in command "date"

bash-3.00$ date
Fri Dec  2 11:02:42 IST 2011


What if I need to look into the calendar? Here it is..


bash-3.00$ cal
   December 2011
 S  M Tu  W Th  F  S
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

This list down only current month. What if I need the entire year?

Its very simple. With the command "cal" mention the year you are interested in

bash-3.00$ cal 2011

                                2011
         Jan                    Feb                    Mar
 S  M Tu  W Th  F  S    S  M Tu  W Th  F  S    S  M Tu  W Th  F  S
                   1          1  2  3  4  5          1  2  3  4  5
 2  3  4  5  6  7  8    6  7  8  9 10 11 12    6  7  8  9 10 11 12
 9 10 11 12 13 14 15   13 14 15 16 17 18 19   13 14 15 16 17 18 19
16 17 18 19 20 21 22   20 21 22 23 24 25 26   20 21 22 23 24 25 26
23 24 25 26 27 28 29   27 28                  27 28 29 30 31
30 31
         Apr                    May                    Jun
 S  M Tu  W Th  F  S    S  M Tu  W Th  F  S    S  M Tu  W Th  F  S
                1  2    1  2  3  4  5  6  7             1  2  3  4
 3  4  5  6  7  8  9    8  9 10 11 12 13 14    5  6  7  8  9 10 11
10 11 12 13 14 15 16   15 16 17 18 19 20 21   12 13 14 15 16 17 18
17 18 19 20 21 22 23   22 23 24 25 26 27 28   19 20 21 22 23 24 25
24 25 26 27 28 29 30   29 30 31               26 27 28 29 30

         Jul                    Aug                    Sep
 S  M Tu  W Th  F  S    S  M Tu  W Th  F  S    S  M Tu  W Th  F  S
                1  2       1  2  3  4  5  6                1  2  3
 3  4  5  6  7  8  9    7  8  9 10 11 12 13    4  5  6  7  8  9 10
10 11 12 13 14 15 16   14 15 16 17 18 19 20   11 12 13 14 15 16 17
17 18 19 20 21 22 23   21 22 23 24 25 26 27   18 19 20 21 22 23 24
24 25 26 27 28 29 30   28 29 30 31            25 26 27 28 29 30
31
         Oct                    Nov                    Dec
 S  M Tu  W Th  F  S    S  M Tu  W Th  F  S    S  M Tu  W Th  F  S
                   1          1  2  3  4  5                1  2  3
 2  3  4  5  6  7  8    6  7  8  9 10 11 12    4  5  6  7  8  9 10
 9 10 11 12 13 14 15   13 14 15 16 17 18 19   11 12 13 14 15 16 17
16 17 18 19 20 21 22   20 21 22 23 24 25 26   18 19 20 21 22 23 24
23 24 25 26 27 28 29   27 28 29 30            25 26 27 28 29 30 31
30 31


Ok, I agree. But what I need to look into the month of Feb for the year 1999?

bash-3.00$ cal 2 1999
   February 1999
 S  M Tu  W Th  F  S
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28


Is that ok?

Be careful while specifying the year. You have to give fully year, iec 2011 not 11. See the difference below.

bash-3.00$ cal 12 2011
   December 2011
 S  M Tu  W Th  F  S
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

bash-3.00$ cal 12 11
   December 11
 S  M Tu  W Th  F  S
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31