56
Oracle FUNCTIONS

Oracle FUNCTIONS. Comment ScreenShot (in 10g) General Example of null Foreign Key: create table deptcs( deptno NUMBER(4) primary key, hiredate DATE,

Embed Size (px)

Citation preview

Oracle FUNCTIONS

Comment ScreenShot (in 10g)

General Example of nullForeign Key: create table deptcs(

deptno NUMBER(4) primary key,hiredate DATE,EMP_ID NUMBER(4),FOREIGN KEY(EMP_ID)REFERENCES empcs (EMP_ID));

create table empcs(EMP_ID number(4) primary key,dname varchar2(20));

insert into empcs values(13,null);insert into deptcs values(1, '02-jan-14', 12);

select * from deptcs // Retrieving valueswhere EMP_ID not IN (select EMP_ID from empcs where dname='cse');

select * from empcswhere dname is null;

To add constraints• Constraints like Unique key, Primary Key and check

constraints can be added if the records in the table is compatible.

• Syntax: Alter table table_name add constraint constraint_name constraint_type(column_name);

Examples:1. To add primary key to Emp_ID column in

Employee table. Alter table Employee add Primary key (Emp_ID );

To add constraints

2. To add unique key to Emp_ID column in Employee table.

Alter table Employee add unique(Emp_ID );

3. To add check constraint to Emp_ID column as Emp_ID > 0, in Employee table.

Alter table Employee add check(Emp_ID > 0);

To add constraints

4.To add foreign key constraint to Emp_ID column of employee table that refers to empid column of department table. Alter table Employee add foreign key (Emp_ID) References department (empid);

Functions

• Functions make the basic query block more powerful, and are used to manipulate data items.

• Functions accept one or more arguments and return one value.

• An argument is a user supplied constant, variable or column reference, which can be passed to a function in the following format:

Function_name(arg1, arg2…)

Types• Single Record Function or Scalar functions: Some

functions operate on only one value at a time.

• Multiple Record Function or group function or aggregate function: Some functions operate on set of values at a time and returns a single result.

Dual Table

• Dual is a dummy table in Oracle owned by the user system.

• SYS owns data dictionary, and dual is the part of data dictionary.

• It contains only one column ‘DUMMY ‘and one row with value ‘X’.

• Besides arithmetic calculations, it also supports date retrieval and it’s formatting.

Dual Table

Select 2*2 from DUAL;• Output: 2*2---------- 4Select Sysdate from DUAL;• Output: SYSDATE---------- 01-jul-04

SINGLE ROW FUNCTIONS

SINGLE ROW FUNCTIONS• Act on single record or row.• Return one result per row• Expect one or more or no user arguments (variables or constants)• May be nested.

Single row functions can be further grouped together by the data type of their arguments and return values:Single row functions can of following types:• Character Functions : for string data type• Number Functions : for number data type• Date Functions : for date data type• Conversion function : for conversion of one data type to another.

Character Functions• Character Functions: Single row character

functions accept character data as input and can return both character and number values.– LOWER (col/value): Converts a string into lower

cases.– UPPER (col/value): Converts a string into upper

cases.– INITCAP (col/value): Converts the string with first

character of the word into upper case and rest in lower cases.

Character Functions

• SELECT LOWER (‘SPARSH’) LOWER, UPPER (‘sparSH’) UPPER, INITCAP (‘JOHN’) INITIAL_CAP FROM TABLE_NAME;

LOWER UPPER INITIAL_CAP ----------- ------------ ------------ sparsh SPARSH John 1 rows selected.

Character Functions• LPAD (col/value, n, ‘char’): Pads the column or

literal values from left, to a total width of n character positions. The leading positions are filled with ‘char’. If string is omitted, value is padded with spaces. An example is given below

• SELECT LPAD (dname,15,‘*’)dept1, LPAD(dname,15)dname2 FROM dept;

Character Functions

DEPT1 DNAME2--------------- ---------------********Physics Physics******Chemistry Chemistry 2 rows selected.

RPAD (col/value, n, ‘char’)

• RPAD (col/value, n, ‘char’) :- Pads the columns or literal values from right, to a total width of n character positions. The leading positions are filled with ‘char’. If string is omitted, value is padded with spaces.

• SELECT RPAD (dname, 15, ‘*’)dept1, RPAD(dname,15)dname2 FROM dept;

RPAD (col/value,n,‘char’)

DEPT1 DNAME2--------------- ---------------Physics******** PhysicsChemistry****** Chemistry 2 rows selected.

SUBSTR (col/value, position, n)

• SUBSTR (col/value, position, n) :- Returns a string of n characters long from the column or literal value, starting at the position number position. If n is omitted, string is extracted from position to the end.

• SELECT SUBSTR (dname,1, 5) DEPTT FROM dept;

SUBSTR (col/value, position, n)

The above example returns the first five characters of each department from DEPT table

DEPTT-----PhysiChemi 2 rows selected.

INSTRINSTR: Returns the location of the substring in a string.INSTR (col/value, ‘string’) :- Finds the character position of first occurrence of string. INSTR (col/value, ‘string’, pos, n): Finds the character position of nth occurrence of string in column or literal values starting at the position number pos. SELECT dname, INSTR (dname, ‘y’) POS1, INSTR (dname, ‘s’,1, 2) POS2 FROM dept;

INSTRHere INSTR (dname, ‘y’) returns the position of first occurrence of y while INSTR (dname, ‘s’, 1, 2) returns the position of 2nd occurrence of s starting from 1st character. As ‘Chemistry’ does not have 2nd ‘s’ so it returns 0.

DNAME POS1 POS2------- --------- ---------Physics 3 7Chemistry 9 0 2 rows selected.

TRIM• Removes all specified characters either from

beginning or end or both.• Syntax: TRIM( [ leading| trailing| both

[<trim_character> from ] ] <string> )

• Leading: Remove trim string from the front of string.

• Trailing : Remove trim string from the end of string.

TRIM

• both: Remove trim string from the front and end of string.

• Trim character: character that will be removed from string.

SELECT TRIM (Both ‘x’ from ‘xxXxxJOHNxx’) RES1 FROM dual; RES1 ------- XxxJOHN

LTRIM/RTRIM(col/value,‘char’)

LTRIM(col/value, ‘char’):- Returns string after removing characters from its left side up to the first character not in the set. RTRIM(col/value, ‘char’):- Returns string after removing characters from its right side up to the first character not in the set. SELECT LTRIM (‘xxxXxxJOHN’, ‘x’) RES1, RTRIM (‘JOHNxxXxxx’,‘x’) RES2 FROM dual;

LTRIM/RTRIM(col/value, ‘char’)

RES1 RES2------- -------XxxJOHN JOHNxxX 1 rows selected.

REPLACE(char, search string, replacement string)

• REPLACE(char string, search string, replacement string):- Returns char string with every occurrence of search string replaced with replacement string.

• If replacement string is omitted or null, all occurrence of search string are removed.

• If search string is null, char string is returned. • It allows to substitute one string for another as well as to

remove character strings.

• SELECT REPLACE (‘JACK AND JUE’,‘J’, ‘BL’) CHANGE FROM dual;

REPLACE(char, search string, replacement string)

CHANGE--------------BLACK AND BLUE 1 rows selected.

Length

• Returns length of a word:• Syntax : LENGTH (word)• Select length (‘IVAN’) length from dual; length 4

Character functionASCII(character) :- It gives the corresponding ASCII value for a given

character. CHR(number) :- It gives the character to the corresponding ASCII value. UID :- Returns an integer that uniquely identifies the current

user. USER :- Returns the current user name. An example of all the above written function is given below SELECT ASCII(‘B’), CHR(75), USER, UID FROM dual;

Character function

ASCII('B') CHR(75) USER UID---------- - ------------------------------

--------- 66 K SCOTT 24 1 rows selected.

Number functions

• These functions are used with numeric data. • The argument to the function is number.

Various number function

• ROUND (col/val, n):- This function rounds the value to n decimal places.

• If n is (-)ve, the no. to left of decimal are rounded.

• If n is omitted then it rounds the value and returns integer value.

Various number function

• SELECT ROUND (45.923,1), ROUND (45.923), ROUND (45.923, -1) FROM dual;

ROUND (45.923,1) ROUND (45.923) ROUND (45.923,-1)--------------- ------------- ---------------- 45.9 46 50 1 rows selected.

TRUNC(col/val, n)

• TRUNC(col/val, n):- Truncates the value to n decimal places. SELECT TRUNC (45.923,1), TRUNC (45.923), TRUNC(45.923,-1)

FROM dual;

TRUNC (45.923,1) TRUNC(45.923) TRUNC(45.923,-1)--------------- ------------- ---------------- 45.9 45 40 1 rows selected.

Examples

Examples

CEIL(col/val)• CEIL(col/val):- Finds smallest integer greater than

or equal to the column/expression value.• SELECT CEIL(11.9), CEIL(11.1), CEIL(11) FROM dual; CEIL(11.9) CEIL(11.1) CEIL(11)---------- ---------- --------- 12 12 11 1 rows selected.

FLOOR (col/val)• FLOOR (col/val):- Finds largest integer less

than or equal to the column or expression value.• SELECT FLOOR (11.9), FLOOR (11.1), FLOOR (11)

FROM dual; FLOOR (11.9) FLOOR(11.1) FLOOR(11) --------------- ----------- --------- 11 11 11 1 rows selected.

NUMBER FUNCTIONSPOWER(col/val, n):- Calculates the power n of col/value, where n is an integer. SQRT(col/val) :- Calculates the square root of the col/value. EXP(n) :- Calculates the value of e raised to the power of n. SIGN(col/val) :- Finds the sign of the col/value according to the

following rule. -1 (-)ve 0 zero +1 (+)ve i.e. If it returns –1 then it means that number is (-)ive . If 0 then number is zero

and if it returns 1 then number is positive.

NUMBER FUNCTIONS

• ABS (col/val) :- Finds the absolute value of the col/value.

• MOD (value1, value2) :- Returns remainder after dividing

value1 by value2. • The syntax for all these functions is given in the following

example. • SELECT POWER(2,4), SQRT(36), EXP(2), SIGN(-44), ABS(-

44), MOD(7,3) FROM dual;

NUMBER FUNCTIONS

POWER(2,4) SQRT(36) EXP(2) SIGN(-44) ABS(-44) MOD(7,3)

---------- --------- --------- --------- --------- --------- 16 6 7.3890561 -1 44 1 1 rows selected.

DATE FUNCTIONS• Date functions are used to manipulate and

extract values from the date column of a table. Following functions are used with dates:

SYSDATE:- SYSDATE is a pseudo column that contains the current date and time. It requires no arguments when selected and returns the current date.

SELECT SYSDATE FROM dual;

DATE FUNCTIONSADD_MONTHS(date, count) : Adds count months to the date. If (-)ve value of count is used then it subtracts months from date. SELECT SYSDATE, ADD_MONTHS(SYSDATE,2) ADDITION, ADD_MONTHS(SYSDATE,-2) SUBTRACTION FROM dual;

DATE FUNCTIONS

SYSDATE ADDITION SUBTRACTION--------- --------- ---------26-MAR-02 26-MAY-02 26-JAN-02 1 rows selected.

DATE FUNCTIONS• LAST_DAY(date) :- Returns the date of the last day of

the month of given date. SELECT SYSDATE, LAST_DAY(SYSDATE) FROM dual; SYSDATE LAST_DAY --------- --------- 26-MAR-02 31-MAR-02 1 rows selected.

DATE FUNCTIONS

• MONTHS_BETWEEN(date2, date1):- Calculates the number of months between two dates (date2- date1).

SELECT SYSDATE, MONTHS_BETWEEN ( SYSDATE, ‘01-JAN-02’)

DIFFERENCE FROM dual;

SYSDATE DIFFERENCE--------- -------------------01-MAR-02 2 1 rows selected.

DATE FUNCTIONS

NEXT_DAY(date, ‘ day’) :- Returns the date of the first week day named by ‘day’ that is after the date named by date. SELECT NEXT_DAY(‘22-AUG-97’, ‘SUNDAY’) FROM dual;NEXT_DAY----------------24-AUG-97 1 rows selected.

DATE FUNCTIONSNEW_TIME(‘date’,‘z1’,‘z2’) :- It gives the date and time in other zone z2

when date and time in this zone z1 are date. SELECT NEW_TIME(‘22-AUG-97’, ‘GMT’, ‘AST’) FROM dual; NEW_TIME----------------22-AUG-97 1 rows selected. Where z1 and z2 can be anyone of AST (Atlantic standard time), BST (Bering standard time), CST (Central Standard Time), EST(Eastern Standard Time), GMT (Greenwich Mean Time), HST (Alaska Hawaii Standard time), PST (Pacific Standard time).

CONVERSION FUNCTIONConverts one data type to another. There are three conversion functions:TO_CHAR(input, format): Converts a date or number into character string. SELECT TO_CHAR( sysdate, ‘ddth/mm/yyyy’) FROM dual; TO_CHAR(SYSDATE)-----------------------------25th/08/1997 1 rows selected.

CONVERSION FUNCTION

SELECT TO_CHAR (320) || ‘New Mandi’ FROM dual; TO_CHAR(320)-----------------------------320 New Mandi 1 rows selected.

CONVERSION FUNCTIONTO_DATE(date, format):- Converts any date format to the default format

( dd-mon-yy). SELECT TO_DATE(‘1997, 25th/JUL’, ‘ yyyy, ddth/mon’) FROM dual; TO_DATE(‘1997, 25th/JUL’)------------------------------------ 25-JUL-97 1 rows selected.

CONVERSION FUNCTIONTO_NUMBER(col/value):- Converts a string to a number. SELECT TO_NUMBER(SUBSTR(‘320, New Mandi’,1,3)) HOUSE_NO from dual; It uses the nesting of functions , first of all SUBSTR function is applied to the data which extracts a string containing first three characters of the input data that is 320. Since it is a string data so TO_NUMBER function converts it to the number. HOUSE_NO--------------- 320 1 rows selected.

GROUP FUNCTIONS

• Group functions operate on set of rows, result is based on group of rows rather than one result per row as returned by single row functions.

• By default all the rows in a table are treated as one group.

• The group by clause of the select statement is used to divide rows into small groups.

GROUP FUNCTIONSThe main group functions available in oracle are • MAX:- Maximum value of expr. Syntax : MAX( [Distinct or All] expr)• MIN:- Minimum value of expr.Syntax : MIN( [Distinct or All] expr)• COUNT(expr) :- Returns the number of records in the table where expr is not null.Syntax : COUNT( [Distinct or All] expr)

GROUP FUNCTIONS

COUNT(*) :- Returns the number of records in the table including null.

SUM(expr) :- Returns the Sum of values of expr, ignoring NULL values.

AVG (expr):- Returns the average of values of expr, ignoring NULL values.

GROUP FUNCTIONSSELECT MAX (sal), MIN (sal), COUNT (sal), AVG (sal), SUM (sal), COUNT (*) FROM emp;

MAX (SAL) MIN (SAL) COUNT (SAL) AVG (SAL) SUM (SAL) COUNT (*)------------- ------------ -------------- ------------- ----------- ------------ 8000 4000 6 5500 33000 7 1 rows selected. All group functions except count(*) Ignore null value.

Count (*) counts the number of records in a table, While count (sal) counts the number of known salaries (ignores NULL).