Operators and Built-in Functions  
Operators Operators are used to manipulate data using the select statement.  Arithmetic Relational Logical Special  String Built-in Functions Character Numeric Date Aggregate/Group Conversion General/Other  
Arithmetic Operators Operators  are   +,  -,  *,  /   SELECT * FROM EMP WHERE SAL + COMM > 3000; The above Example will select the employee(s) whose salary + commission is more than 3000.   SELECT * FROM EMP WHERE SAL – COMM > 2000; The above example will select the employee(s) whose salary – commission is more than 2000;    SELECT * FROM EMP WHERE COMM > SAL * 10/100; The above example will select the employee(s) whose commission is more than 10% of their salary.
Logical Operators AND  (logical AND),  OR  (logical OR) and  NOT  (logical NOT). SELECT * FROM EMP  WHERE JOB = ‘CLERK’ AND DEPTNO=20 ; The above example will select the employee(s) who is working in dept 10 and he should be a CLERK. In the above case, both the job and deptno should satisfy the given condition i.e., both the conditions should be true. SELECT ENAME FROM EMP  WHERE JOB=’SALESMAN’ OR JOB=’ANALYST’; The above example will select the employee(s) whose  JOB is either SALESMAN or ANALYST. SELECT * FROM EMP  WHERE DEPTNO NOT IN (10, 20); The above example will select the employee(s) who are not working in department 10 and 20.
Relational Operators   =  Equal to <>, !=,^= Not Equal to < Less than > Greater than >= Greater than or  <= Less than or  Equal to
Examples for Relational Operators: (= , <>) SELECT * FROM EMP  WHERE DEPTNO = 10;   The above example will select the employee(s) who are working in deptno 10;   SELECT * FROM EMP WHERE DEPTNO <> 10; The above example will select the employee(s) who are not working in deptno 10.    
Example for > ,>=, <. <= SELECT * FROM EMP WHERE  SAL > 3000 ; The above example will select the employee(s) who is getting salary from 3001 onwards. SELECT * FROM EMP WHERE  SAL >= 3000 ;   The above example will select the employee(s) who is getting salary from 3000 onwards. SELECT * FROM EMP WHERE  SAL < 2000 ;   The above example will select the employee(s) who is getting salary below 2000; SELECT * FROM EMP WHERE  SAL <= 2000 ; The above example will select the employee(s) who is getting salary 2000 and less.
Special Operators   LIKE, BETWEEN AND, IN, ANY and ALL   Examples: SELECT * FROM EMP WHERE ENAME  LIKE  ‘ALLEN’;  The above example will select the employee(s) whose name is exactly like ‘ ALLEN’. Even it will not fetch the employee whose name is ‘allen’ or ‘ Allen’ or ‘Allen’.   SELECT * FROM EMP WHERE SAL  BETWEEN  1500  AND  3500 ;   The above example will select the employee(s) who is getting salary between 1500 and 3500; ANY, IN and ALL operators will be explained more in SUB-QUERIES.
String Operators   %   (percentage) _  (underscore) ||  (concatenation)   The above operators are used to compare the string values.  
Examples:  SELECT * FROM EMP WHERE ENAME LIKE ‘E%’; The above example will select the employee(s) who’s name  starts with ‘E’ followed by any number of characters .   SELECT * FROM EMP WHERE ENAME LIKE ‘S_ _ _ _ _’; The above example which uses the _(underscore) after ‘S’, will fetch the employee(s) who’s  name starts with ‘S’ and whose length of name is exactly five characters . SELECT ENAME||JOB||HIREDATE FROM EMP; The above example will list the ENAME, JOB, HIREDATE  column values joined together  without any space in between.  
Built-in SQL functions SQL provides a number of predefined functions that can be called from within an SQL statement. It is used to manipulate data items.   Advantages of Functions   Functions can be used to perform complex calculations on data.   Functions can modify individual data items.   Functions can very easily manipulate output for group of rows.   Functions can alter date formats for display.
Types of Functions   Ø        Character functions Ø        Arithmetic functions Ø        Date functions Ø  Conversion functions  Ø        Aggregate / Group functions
Character Functions CHR Syntax: CHR(x) Purpose: Returns the character that has the value equivalent to x in the database character set. CHR and ASCII are opposite functions. CHR returns the character given the character number, and ASCII returns the character number given the character. Example: SELECT CHR(37) a, CHR(100) b, CHR(101) c from dual; Output: A  B C - - - % d  e
What is DUAL? Dual is a small Oracle table created for testing functions or doing quick calculations which has one row and column. Since Oracle’s many functions work on both columns and literals. Some Oracle functions use just literals in these situations DUAL table can be used.  Structure of Null table: Name  Null?  Type ----------------------------------------------------- -------- ----------------- DUMMY  VARCHAR2(1) Select * from dual; D - X
CONCAT   Syntax: CONCAT (String1, String 2)   Purpose  Returns  string1  concatenated with  string2.  This function is identical to the || operator.   Example:   SELECT CONCAT(‘Information  ’, ‘  Technology’)  “Computer” from dual;   Output: Computer ------------- Information Technology  
INITCAP   Syntax: INITCAP( String )   Purpose: Returns  string  with the first character of each word capitalized and the remaining characters of each word in lowercase.  Characters that are not letters are unaffected.   Example:   SELECT INITCAP (‘time is gold’) “Time” from dual;   Output: Speech ----------------------- Time is gold
LOWER   Syntax: LOWER(String)   Purpose: Returns  string  with all characters in lowercase.  Any characters that are not letters will not convert.  If  string  has the CHAR datatype, the result is also CHAR.  If  string  is VARCHAR2, the result is VARCHAR2.   Example:   SELECT LOWER (‘EVERYTHING IN LOWER CASE’) “lower” from dual;    Output:  lower -------------- everything in lower case  
UPPER   Syntax: UPPER(string)   Purpose  Returns  string  with all letters in uppercase.  If string has datatype CHAR, the return value is also CHAR.  If string has datatype VARCHAR2, then the return value is VARCHAR2.  Any Characters that are not letters are left intact in the returned value. Example:  SELECT UPPER (‘print in uppercase’) “UPPER” FROM dual; Output: UPPER PRINT IN UPPERCASE
LPAD Syntax: LPAD(String1,  x [,string2]) Purpose : Returns string1 after padding string2 from left to length x. If  string2  is less than  x  characters, it is duplicated as necessary.  If  string2  is more than  x  characters, only the first required  x  characters are used.  If  string2  is not specified, it defaults to a single blank for each space.  Examples: SELECT LPAD (‘have a good day’,18) “First” from dual; Output: First ----- have a good day
SELECT LPAD (‘have a good day’, 20, ‘XY’) “Demo” from dual;   Output: Demo XYXYXhave a good day   SELECT LPAD (‘have a good day’, 16, ’XY’) “Test” from dual;   Output: Test Xhave a good day
RPAD   Syntax: RPAD(String1,x[,string2])   Purpose: Returns  string1  padded on the right to length x with the characters in  string2.  If  string2  is less than x characters, it is duplicated as necessary.  If  string2  is more than x characters, only the first x are used.  If  string2  is not specified, it defaults to a single blank.    Examples:   SELECT RPAD (‘Cricket’, 10, ‘!’) “First” from dual;   Output: First ---------- Cricket!!!  
SELECT RPAD(‘Cricket’, 10, ‘AB’) “Second” from dual;   Output: Second ---------- CricketABA   SELECT RPAD ('Cricket', 3) &quot;Third&quot; from dual;   Output:  Thi --- Cri
RTRIM   Syntax: RTRIM(String1[,string2])   Purpose: Returns  string1  with the rightmost characters appearing in  string2  removed.  String2  defaults to a single blank.  The database will scan  String1,  starting from the rightmost position.  When the first character not in  String2  is encountered, the result is returned.    Examples: SELECT RTRIM(‘This is a string  ’)  “First” from dual; Output:   First     This is a string  
SELECT RTRIM(‘This is a stringxxxxx’, ‘x’) “Second” from dual;   Output: Second ---------------- This is a string   SELECT RTRIM(‘This is a string as well’, ‘well’) “Third” from dual;   Output: Third -------------------- This is a string as
TRIM  This function can used instead of LTRIM and  RTRIM   Example:     SELECT TRIM(‘  INDIA  ‘) FROM DUAL;   Output:  TRIM( ----- INDIA  
REPLACE Syntax: REPLACE (String, search_str[, replace_str])   Purpose : Returns  string  with every occurrence of  search_str  replaced with  replace_str.  If  replace_str  is not specified, all occurrences of search_str are removed. Examples: SELECT REPLACE (‘This and That’, ‘Th’, ‘B’)”First” from dual;   Output: First Bis and Bat  
SELECT REPLACE (‘This and That’, ‘Th’)”Second” from dual;   Output: Second ------------ is and at   SELECT REPLACE (‘This and That’, null) “Third” from dual;   Output: Third ------------ This and That
SUBSTR   Syntax  :  SUBSTR ( string ,  a  [,  b ])   Purpose: Returns a portion of  string  starting at character  a, b  characters long . If  a  is 0, it is treated as 1(the beginning of the string).  If  b  is positive, characters are returned counting from the left.  If  b  is negative, characters are returning starting from the end of  string,  and counting from the right .  If  b  is not present, it defaults to the entire string.  If  b  is less than 1, NULL is returned.  Examples: SELECT SUBSTR('He is a Good Boy', 2) &quot;First&quot; from dual; Output: First e is a Good Boy SELECT SUBSTR('He is a Good Boy', 2, 4) &quot;Second&quot; from dual Output: Second e is
SELECT SUBSTR ('He is a Good Boy', -5) &quot;Third&quot; from dual   Output: Third ----- d Boy   SELECT SUBSTR ('He is a Good Boy', -5, 3) &quot;Four&quot; from dual   Output: Fou --- d B
TRANSLATE Syntax: TRANSLATE ( string , from_str , to_str ) Purpose: Returns  string  with all occurrences of each character in  from_str  replaced by the corresponding character in  to_str. If  from_str  is longer than  to_str,  any extra characters in  from_str  not in to_str are removed from  string , since they have no corresponding characters.  to_str cannot be empty.  If any argument to TRANSLATE is null, the result is NULL as well.   Examples:   SELECT TRANSLATE(‘abcdefghij’,’abcdef’,’123456’) from dual;   Output: TRANSLATE( 123456ghij SELECT TRANSLATE (‘abcdefghij’, ‘abcdefghij’, ‘123456’) from dual;   Output: TRANSL 123456  
SOUNDEX   Syntax: Soundex( string )   Purpose : Returns the phonetic representation of  string.  This is useful for comparing words that are spelled differently but sound alike. Example: SELECT ENAME FROM EMP  WHERE SOUNDEX(ENAME) = SOUNDEX('SMEETH');   Output: ENAME ---------- SMITH
Date Functions   The date functions take arguments of type DATE,  except  for the MONTHS_BETWEEN function, which returns a  NUMBER, all of the functions return DATE values.  
SYSDATE Syntax: SYSDATE Purpose: Returns the current date and time, of type DATE.  Takes no arguments.  When used in distributed SQL statement, SYSDATE returns the date and time of the local database. ( For instance if the current date is 4th May 2002) Example:    SELECT SYSDATE FROM DUAL; Output:  SYSDATE    ---------   05-MAY-02
ADD_MONTHS Syntax: ADD_MONTHS ( d,x  ) Purpose: Returns the date  d  plus  x  months or  d  minus  x . x can be any integer.  Example: SELECT ADD_MONTHS(‘02-MAR-88’, 3),  ADD_MONTHS(‘30-JAN- 00’, 1)  FROM DUAL;   Output:  ADD_MONTH ADD_MONTH ------------------  ------------ ------ 02-JUN-88  29-FEB-00
MONTHS_BETWEEN Syntax:  MONTHS_BETWEEN(DATE1,DATE2) Purpose: Returns the number of months between date1 and date2.  If both date1 and date2 have the same day component, or if both are the last day of their respective months, then the result is an integer. Otherwise, the result will contain the fractional portion of a 31-day month. Example: SELECT MONTHS_BETWEEN('12-APR-71', '12-MAR-97') &quot;First&quot;,      MONTHS_BETWEEN ('12-APR-71', '12-MAR-60') &quot;Second&quot;  FROM dual;   Output:   First Second ------- ----------   -311 132.67742
LAST_DAY   Syntax: LAST_DAY( d) Purpose:  Return the date of last day of the month that contains  d.  This function can be used to determine how many days are left in the current month. Example: SELECT LAST_DAY('12-APR-71') &quot;CURRENT&quot;,  LAST_DAY('12-APR-71') - TO_DATE('12-APR-71')  &quot;Days left&quot; FROM dual;   Output:   Current Days Left   ------- ---------- 30-APR-71   18
NEXT_DAY Syntax: NEXT_DAY(d, string) Purpose  : This function returns the date of next specified day of the week(string)  after the  d (date). Example: SELECT NEXT_DAY('07-MAY-02','MONDAY') FROM DUAL; Output: NEXT_DAY( --------- 13-MAY-02
ROUND   Syntax: ROUND(d,  [, format) Purpose  : Returns the date d to the unit specified by format. If format is not specified, it defaults to 'DD', which rounds d to the nearest day. Example:   SELECT ROUND(TO_DATE(‘12-APR-71’), ‘MM’) &quot;Nearest Month&quot;  FROM dual;   Output : Nearest Month ----------------- 01-APR-71   (1-15 it will round to the same month, 16 and after - next month)
TRUNC   Syntax: TRUNC(d, [,format]) Purpose: Returns the date d truncated to the unit specified by format.  If format is not specified, it defaults to 'DD', which truncates d to the nearest day. Example: SELECT TRUNC(   FROM dual;   Output:  First Day -------------- 01-JAN-71
Date Arithmetic Applying the arithmetic operators to dates and numbers are described. When one date value is subtracted from another, the result is a number.   Examples of valid date arithmetic expressions follow:   Example 1:  Adding to Date   SELECT SYSDATE, SYSDATE + 1 &quot;Tomorrow&quot; FROM dual;   Output: SYSDATE  Tomorrow -------------- ------------- 13-NOV-95 14-NOV-95  
Subtracting from Date Example 1: SELECT TO_DATE('12-APR-71 12:00:00', 'DD-MON-YY HH24:MI:SS')  - TO_DATE(15-MAR-71 15:00 -MON-YY HH24:MI:SS')  &quot;Difference&quot; FROM dual;   Output: Difference --------------   27.875  
Example 2:   SELECT TO_DATE('10-AUG-98') - TO_DATE('12-FEB-98') FROM DUAL;   Output:  TO_DATE('10-AUG-98')-TO_DATE('12-FEB-98') --------------------------------------------------------------   179  
Conversion Functions   TO_NUMBER   Syntax: TO_NUMBER( string  [, format [,nlsparams]])   Purpose:   Converts the CHAR or VARCHAR2 string to a NUMBER value. If format is specified, string should correspond to number format. Example: SELECT TO_NUMBER('25') + TO_NUMBER('50') &quot;TOTAL&quot; FROM DUAL;   Output: TOTAL     75
TO_CHAR (WITH NUMBERS)   Syntax: TO_CHAR( num,  [,format[, nlsparams ]])   Purpose: Converts the NUMBER argument  num  to a VARCHAR2.   If  format  not specified, the resultant string will have exactly as many characters as necessary to hold the significant digits of  num. Example: SELECT TO_CHAR(123) FROM DUAL;   Output TO_ 123
TO_CHAR (WITH DATE) Syntax: TO_CHAR(d,[,format [,nlsparams]]) Purpose: TO_CHAR can also be used for the conversion of dates values to a specified character format. TO_CHAR allows us to format the date in various different ways. Example 1: SELECT TO_CHAR(SYSDATE, ‘DAY DDSPTH MONTH YEAR') FROM DUAL; Output : TO_CHAR(SYSDATE,'DAYDDSPTHMONTHYEAR') --------------------------------------------------------------------- WEDNESDAY  FOURTEENTH  MARCH  TWO THOUSAND ONE  
Example 2: SELECT TO_CHAR(HIREDATE, 'DDTH MONTH YEAR') &quot;JOINING DATE&quot;  FROM EMP  WHERE EMPNO = 7788; Output: JOINING DATE ------------------------------------------------- 09TH DECEMBER  TWENTY EIGHTY-TWO Example3: SELECT TO_CHAR(TO_DATE('14-MAR-01'), 'RM') FROM  DUAL; Output: TO_C   III RM – Roman Numeral Month 
Group / Aggregate Functions
Group / Aggregate Functions Group functions are those statistical functions, which gives information about a group of value taken as whole.  The aggregate function produce a single value for an entire group or table.  In all group functions, NULLs are ignored.  These functions are valid in the select list of a query and the GROUP BY clause only.
AVG Syntax: AVG([DISTINCT | ALL]col) Purpose: Returns the average of the column values.   Example:   SELECT AVG(sal) FROM EMP;
COUNT  Syntax  :  COUNT(*|[DISTINCT |ALL]col) Purpose  :  Count function determines the number of rows or non-NULL column values.    If * is passed, then the total number of rows is returned.   Example 1: SELECT COUNT(*) FROM EMP; Example 2:   SELECT COUNT(deptno) FROM EMP; Example3:   SELECT COUNT(DISTINCT deptno) FROM EMP;
MAX   Syntax: MAX([DISTINCT | ALL] coL) Purpose  : Returns the maximum value of the select list item.    Example 1: SELECT MAX(SAL) FROM EMP; Example 2:    SELECT MAX(LENGTH(ENAME)) FROM EMP; This example returns the length of the longest name in the EMP table:
MIN   Syntax  : MIN([DISTINCT | ALL] coL)   Purpose:  Returns the maximum value of the select list item.  Example: SELECT MIN(COMM) “MIN-COMM”, MIN(SAL) “MIN-SAL” FROM EMP;   Output: MIN-COMM  MIN-SAL ----------------- -------------   0  800
SUM   Syntax  : SUM([DISTINCT | ALL] Col)   Purpose: Returns the sum of the values for the select list item.   Example 1:   SELECT SUM(SAL) FROM EMP;  
Other / General Functions DECODE Syntax: DECODE( base_expr,   compare1, value1,   compare2, value2,    . . .      default ) Purpose  : The DECODE statement is similar to a series of nested IF-THEN-ELSE statements.  The  base_expr  is compared to each of  compare1, compare2 , etc., in sequence. If  base_expr  matches the i th  compare item, the  i th  value is returned. If  base_expr  doesn't match any of the compare values,  default  is returned.  Each compare value is evaluated in turn.  If a match is found, the remaining  compare  values, if any, are not evaluated.  A NULL  base_expr  is considered equivalent to a NULL compare value.  
Example 1:   SELECT DECODE(10, 10, 'TEN', 20, 'TWENTY', 30, 'THIRTY') &quot;MATCH&quot;  FROM DUAL;   Output: MAT TEN  
Example 2:   SELECT DECODE(50, 10, ‘TEN’, 20, ‘TWENTY’, 30, ‘THIRTY’, ‘NEW VALUE’) FROM DUAL;   Output: DECODE(50 --------- NEW VALUE   Example 3:   SELECT DECODE(NULL, ‘A’, ‘ARUN’, NULL, ‘NOVALUE’, ‘B’, ‘BHARATH’) FROM DUAL;   Output: DECODE( ------- NOVALUE
GREATEST Syntax  :  GREATEST (expr1[,expr2]…)   Purpose : Returns the greatest expression of its arguments. Each expression is implicitly converted to the type of expr1 before the comparisons are made.  Example 1:   SELECT GREATEST (10, '7', -1) FROM dual;   Output: GREATEST (10, '7', -1) ---------------------   10   Example 2:   SELECT GREATEST(‘ASHWIN’, ‘SOFIA’) FROM DUAL;   Output: GREAT --------- SOFIA
LEAST   Syntax  : LEAST(expr1 [, expr2]…)   Purpose : This function returns the least value in the list of expressions.  LEAST behaves similarly to GREATEST, in that all expressions are implicitly converted to the datatype of the first.  Example 1:   SELECT LEAST (10, '7', -1) FROM dual; Output: LEAST(10,'7', -1) ----------------   -1   Example 2:   SELECT LEAST ('ASHWIN', 'SOFIA') FROM DUAL;   Output: LEAST( ------ ASHWIN
NVL Syntax: NVL( expr1, expr2 ) Purpose: If  expr1  is NULL, returns  expr2;  otherwise, returns  expr1.  The columns with NULL values are ignored in all of the group functions such as sum, Avg etc.  The NULL function helps in substituting a value in place of a NULL.    Example:  SELECT  NVL (null, ‘this is a null value’)  “NullTest” FROM DUAL; Output :  NullTest    ---------------------  this is a null value   SELECT ENAME, SAL, COMM, SAL + COMM “GROSS SAL”, SAL + NVL (COMM, 0) “CORRECT SAL” FROM EMP;   (The above command will substitute 0 for commission where the commission is NULL).
UID Syntax  : UID   Purpose : Returns an integer that uniquely identifies the current database user. UID takes no arguments.   Example: This example shows a sample SQL*Plus session. SQL> Connect Scott/Tiger Connected.  SQL> SELECT UID FROM dual; UID 8 SQL> connect system/manager Connected.    SQL> SELECT UID FROM dual; UID 5
USER   Syntax  : USER   Purpose : Returns a VARCHAR2 value containing the name of the current Oracle user. USER takes no arguments.   Example:  This example shows a sample SQL*PLUS statements   SQL> connect Scott/Tiger   Connected.  SQL> SELECT USER FROM dual; USER SCOTT SQL> Connect Sys/Change_on_install    Connected. SQL> SELECT USER FROM dual; USER SYS