Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 Oracle FUNCTIONS

2 Comment ScreenShot (in 10g)

3 General Example of null Foreign 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 values where EMP_ID not IN (select EMP_ID from empcs where dname='cse'); select * from empcs where dname is null;

4 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 );

5 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);

6 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);

7 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…)

8 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.

9 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.

10 Dual Table Select 2*2 from DUAL; Output: 2*2 ---------- 4 Select Sysdate from DUAL; Output: SYSDATE ---------- 01-jul-04

11 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.

12 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.

13 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.

14 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;

15 Character Functions DEPT1 DNAME2 --------------- ********Physics Physics ******Chemistry Chemistry 2 rows selected.

16 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;

17 RPAD (col/value,n,‘char’) DEPT1 DNAME2 --------------- Physics******** Physics Chemistry****** Chemistry 2 rows selected.

18 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;

19 SUBSTR (col/value, position, n) The above example returns the first five characters of each department from DEPT table DEPTT ----- Physi Chemi 2 rows selected.

20 INSTR INSTR: 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;

21 INSTR Here INSTR (dname, ‘y’) returns the position of first occurrence of y while INSTR (dname, ‘s’, 1, 2) returns the position of 2 nd occurrence of s starting from 1 st character. As ‘Chemistry’ does not have 2 nd ‘s’ so it returns 0. DNAME POS1 POS2 ------- --------- --------- Physics 3 7 Chemistry 9 0 2 rows selected.

22 TRIM Removes all specified characters either from beginning or end or both. Syntax: TRIM( [ leading| trailing| both [ from ] ] ) Leading: Remove trim string from the front of string. Trailing : Remove trim string from the end of string.

23 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

24 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;

25 LTRIM/RTRIM(col/value, ‘char’) RES1 RES2 ------- XxxJOHN JOHNxxX 1 rows selected.

26 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;

27 REPLACE(char, search string, replacement string) CHANGE -------------- BLACK AND BLUE 1 rows selected.

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

29 Character function ASCII(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;

30 Character function ASCII('B') CHR(75) USER UID ---------- - ------------------------------ -------- - 66 K SCOTT 24 1 rows selected.

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

32 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.

33 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.

34 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.

35 Examples

36

37 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.

38 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.

39 NUMBER FUNCTIONS POWER(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.

40 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;

41 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.

42 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;

43 DATE FUNCTIONS ADD_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;

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

45 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.

46 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.

47 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.

48 DATE FUNCTIONS NEW_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).

49 CONVERSION FUNCTION Converts 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) ----------------------------- 25 th /08/1997 1 rows selected.

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

51 CONVERSION FUNCTION TO_DATE(date, format):- Converts any date format to the default format ( dd-mon-yy). SELECT TO_DATE(‘1997, 25 th /JUL’, ‘ yyyy, ddth/mon’) FROM dual; TO_DATE(‘1997, 25 th /JUL’) ------------------------------------ 25-JUL-97 1 rows selected.

52 CONVERSION FUNCTION TO_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.

53 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.

54 GROUP FUNCTIONS The 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)

55 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.

56 GROUP FUNCTIONS SELECT 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 330007 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).


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

Similar presentations


Ads by Google