Oracle Sql & PLSQL Complete guide

1,151
-1

Published on

Complete Description about the SQL and PLSQL,, the best ppt i have ever seen,,, Easy and Brief guide and description about the Oracle

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,151
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
73
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Oracle Sql & PLSQL Complete guide

  1. 1. What is a data base? • Data base is a structure or a component used for storing the data • Data base can be implemented using file systems either in C or C++ or Java
  2. 2. Web site For a bank User Open account Account Data base Java C program
  3. 3. Create table • Data in a data base is stored in the form of tables • How to create a table? – Create table <table name>(<col> <data type>); • List of all the available data types to be used in Oracle for defining columns can be obtained by using the following command – SQL > VAR X DATE (SQL > is not a part of the command) • CREATE TABLE ACC1(ANO NUMBER, ANAME CHAR(10));
  4. 4. ALTER • Modify size of a column – Alter table <table name> modify(<col> <data type[(size)]>); • alter table acc1 modify(aname char(7)); • alter table acc1 modify(aname char(10)) • Add a column to a table – Alter table <table name> add(<col> <data type>); • alter table acc2 add(ano number); • alter table acc2 add(atype varchar2(10), mbno number); • Delete a column from a table – Alter table <table name> drop column <col name>; • alter table acc2 drop column atype; • alter table acc2 drop(aname, mbno); • Rename a column in a table – Alter table <table name> rename column <old name> to <new name>; • alter table acc2 rename column ano to acc_no;
  5. 5. • Column size can be decreased if and only if the column is empty • Column size can be increased whether or not the column is empty • If you want to reduce the size of a column even though the column is containing data then that column has to be declared as varchar2(size). Because varchar2(size) type alocates variable no of memory locations at run time. Whereas char(size) will allocate fixed number of memory locations at run time • Size of value in a column must be <= max size of a column • Col data type can be changed into a compatible type(char to varchar2) even though the column is not empty. But col type can be changed into a incompatible type(char to number) if the col is empty • When you are changing the data type from char to vachar2 you cannot decrease the size of a column • In a table, you should have atleast 1 column ie you cannot delete all the columns from a table
  6. 6. number(p,s) ● This is a special number type that can be used for controlling the no of digits before decimal and mostly we use this type for storing decimal numbers ● S is the scale of a number ie it defines the min no of digits after decimal ● Max No of digits before decimal is defined using p – s which is the precision of a number ● Less then min is allowed but more than max is not allowed ● Number validation will be done only based on precision and not on scale ● Default precision for any number type is 38
  7. 7. INSERT • This command is used for inserting data into columns of a table • Syntax for using this command – Insert into <table name> values(<val 1>, <val 2>); • insert into stud_test values(102); – Insert data into specific columns of a table • insert into stud_test1(sno) values(102); – Define an insertion order • insert into stud_test1(sname, sno) values('james', 103) – Insert data at run time • insert into stud_test1 values(&sno, '&sname');
  8. 8. Contd.. • insert into stud_test1 values(&123, '&456'); – Any character succeeding & in insert command will be treated as a value and not as a name of the column. Hence you can provide any text succeeding & • Insert command inserts values into columns of a table depending on No, type and order of those values • Insert command always inserts values as new row
  9. 9. NULL VALUE • When you do not insert data into a column of a table for a specific row then by default a NULL value will be inserted into that column by the data base • NULL value does not occupy space in memory • Null value is independent of a data type of any column in a table
  10. 10. UPDATE • This command inserts values for the existing rows • This command can also be used for deleting values from a cell of a table without the need for deleting a row and a column • Syntax – Update <table name> set <col name> = <new value> [where <condition>]; • update stud_test1 set mbno = 301 where sno = 101; • update stud_test1 set mbno = null where mbno = 301;
  11. 11. DELETE • This command is used for deleting specific or all the rows from a table • Syntax – Delete from <table name> [where <condition>];
  12. 12. Truncate • This command can also be used for deleting all the rows from a table • Syntax – Truncate table <table name>; • Truncate command cannot be rolled back because it is a AUTO COMMIT operation ie changes committed cannot be rolled back. But DELETE is not a AUTO COMMIT operation. Hence it can be ROLLED BACK/
  13. 13. DROP • This command can be used for permanently deleting the table from a data base • Syntax – Drop table <table name>; • drop table stud_test;
  14. 14. Select • This command is used to retrieve data from a table • Syntax – Select <col name> from <table name> [where <condition>]; • select ename, job, sal from emp; • select * from emp ( * denotes all the columns in a table)
  15. 15. OPERATORS
  16. 16. Relational operators • display the details of those emps who are getting a sal > 20000 – SELECT * FROM EMP1 WHERE SAL > 20000 • Display the details of those emps who are getting a sal between 10000 and 20000 – select * from emp1 where sal >= 10000 and sal < 20000 • Display the details of those emps who are either clerks or getting a sal < 20000 – select * from emp1 where job = 'clerk' or sal < 20000
  17. 17. SQL OPERATORS
  18. 18. Between<lower> and <upper> • This operator is used as a replacement for relational(>, <) and logical operators(AND, OR) • In this operator lower and upper values are inclusive if they are of number or date types • In this operator upper limit is not inclusive when it is of a char type • The lower limit must be <= upper limit – select * from emp1 where sal between 10000 and 20000
  19. 19. IS NULL • This operator can be used for testing for the existence of NULL values in any column of a table • Display the details of those employees who are not having any job • select * from emp1 where job is null • Nul l value cannot be compared. Hence you cannot use relational operators for comparing NULL value with a column • Therefore IS NULL operator has to be used for that purpose
  20. 20. Concatenation operator (||) • This operator should be used for appending a string to a variable or a column • Display the data from emp table in the following format for all the rows – Ravi is getting a sal of Rs. 20000 • select ename || ' is getting a sal of Rs. ' || sal from emp1 – “Ravi is an employee” • select ' " '||ename || ' is an employee " ' from emp1
  21. 21. IN OPERATOR • This operator is used to compare multiple values with a single column • In this operator, the values must be of the same type and they should belong to only 1 column • This operator is a replacement for OR operator – select * from emp1 where job in('clerk', 'manager')
  22. 22. Like operator • This operator is used for comparing characters in a string from a specific position • % ignores variable number of characters • _ ignores only 1 char • Display the details of thos e emps whose name is starting with “r” – select * from emp1 where ename like 'r%‘ • Display the details of those emps who have ‘naidu’ as their name – select * from emp1 where ename like '%naidu%‘ • Display the details of those emps whose name is starting with “a” as the second char – select * from emp1 where ename like '_a%‘ • Display the details of those emps whose first char is N and third char is I – select * from emp1 where ename like 'n_i%';
  23. 23. • Display the details of those emps whose name is starting with a char which is between A and L – select * from emp1 where ename between 'a%’ and 'l%'
  24. 24. FUNCTIONS
  25. 25. Description • Function is a sub program which performs a specific task • Every function utmost returns only 1 value • Functions in Oracle data base will be used or defined for – Performing arithmetic calculations which are not possible using arithmetic operators – Formatting text – Type casting ie converting one type of data into another
  26. 26. Using functions • Functions can be either built in or user defined Ie there are 2 types of functions – System defined functions – User defined functions • Usage of a function is subject to calling a function – Select <function name(args)> from <table name>;
  27. 27. System defined functions • Number functions • String functions • Date and time functions • Conversion functions • Aggregate functions
  28. 28. NUMBER FUNCTIONS
  29. 29. Ceil(arg1) • This function will return the succeeding integer value for the decimal value passed as an argument • This function will accept only 1 parameter which is of a number type – select ceil(10.35) from emp1 • When you pass a negative argument to this function, it will return the current integer value – select ceil(10.35) from emp1
  30. 30. Floor(arg1) • This function will return the preceding integer value by accepting a decimal value as an argument – select floor(-10.9999) from emp1 • When you pass a negative argument, this function will return the preceding negative value
  31. 31. Round(arg1, [arg2]) • This function will return either the preceding or succeeding integer value depending on the decimal value ie if the decimal value is >= 0.5 then succeeding integer value will be returned else if the decimal value is < 0.5, preceding integer value will be returned • The second argument to be passed to this function is an optional argument. But it signifies the no of decimal places up to which the number has to be rounded – select round(10.567899991345, 4) from dual
  32. 32. Power(arg1, arg2) • This function returns the power of 2 numbers • It accepts 2 arguments – Arg1 is the base which can be –ve or +ve – Arg2 is the exponent which can be –ve or +ve • Using this function anything raised to the power of 0 will always return 1 including 0
  33. 33. Sqrt(arg1) • This function returns the square root of a number • Arg1 must be always +ve • If it is negative then the function should return a imaginary number which is represented as a complex number. • A complex number can be stored as a class type • Therefore the function should return an object which is not possible in ORACLE
  34. 34. MOD(ARG1, ARG2) • This function will return the remainder of a division of 2 numbers • Arg1 is the numerator and arg2 is the denominator • Sign of the remainder must be same as sign of the numerator • Arg1 and arg2 can be of decimal types also
  35. 35. Abs(arg1) • This function will convert a –ve number into a +ve number • Arg1 can be +ve or -ve
  36. 36. STRING FUNCTIONS
  37. 37. CASE CONVERSION FUNCTIONS • Lower(arg1) – Arg1 is of a char type – This function will return the text in lower case • Upper(arg1) – Arg1 is of a char type – This function will return the text in upper case • Initcap(arg1) – Arg1 is of a char type – This function will return the text in Title case • Argument to be passed to a string function can be a – Constant – Column name – Variable – Function
  38. 38. Substr(a1,a2,a3) • This function is used for extracting a part of a text from a given text • Arg1 is the main string • Arg2 is the starting position of the text to be extracted • Arg3 is the no of chars to be extracted from the start position of the sub string • Arg1 can also be passed as a number type
  39. 39. instr(string, char) ● This function returns the position of the first occurrence of a char in a string ● Arg1 is the string ● Arg2 is the char for which you need to know the position ● Eg : select instr('welcome', 'e') from dept
  40. 40. Length(arg1) • This function returns the no of chars in a text • Arg1 is of a char type – select length('welcome to cmc and thank you') from dept; • Arg1 can also be of a number type – select length('welcome to cmc and thank you') from dept;
  41. 41. Concat(arg1, arg2) • This function will concatenate 2 different strings • Arg1 and arg2 can be of char or number types – select concat(ename, concat(' ', sal)) from emp – select concat(ename, concat(' is a ', job)) from emp • Disadvantages with this function – You cannot pass more than 2 args to this function – Position and number of the characters to be added must be explicitly provided as an argument
  42. 42. Padding functions • These function are used to resolve the limitations with concat function • These functions are used to add chars from left or right side of a string • Lpad(arg1, arg2, arg3) – Arg1 is a string or number – Arg2 is the no of chars existing in the main string + the number of characters to be added from the left side of the string – Arg3 is the chars to be added from the left side • Rpad(arg1, arg2, arg3) – Arg1 is a string or number – Arg2 is the no of chars existing in the main string + the number of characters to be added from the right side of the string – Arg3 is the chars to be added from the right side
  43. 43. Contd.. • select lpad('kumar', 8, 'Mr.’) from dept • select rpad('kumar', 15, '*') from dept; • select lpad(job, length(job) + 10, '$') from emp
  44. 44. Trimming functions • These functions are used to trim the chars from left or right side of a string • Ltrim(arg1, arg2) – Arg1 is the string – Arg2 is the characters you want to trim from the LHS – select ltrim('welcome', 'wel') from dept; • rtrim(arg1, arg2) – Arg1 is the string – Arg2 is the characters you want to trim from the RHS – select rtrim('welcome', 'come') from dept;
  45. 45. Contd.. • Chars to be trimmed either from left or right side must be the first most chars starting from left or right • In ltrim or rtrim, if the char to be trimmed is having a multiple occurrence continuously then every occurrence will be trimmed(“cccbc”). Else if the occurrence is alternating then only the first occurrence will be trimmed(“cfcfcf” ) based on the chars in the trim set • Trim(arg1) – This trims spaces from left and right side of a string – select trim('c' from 'cbcbcbc') from dept
  46. 46. Replace and translate • These functions are used for replacing old chars with new chars in a string • These functions will accept 3 arguments – Arg1 is a main string – Arg2 is the old chars you want to replace in the main string – Arg3 is the new chars to you want to substitute in place of old chars – select translate('abcdef', 'def', 'pqr') from dept – select replace('abcdef', 'def', 'pqr') from dept
  47. 47. Translate Replace The no of new charas must be <= the old chars to be replaced The no of new chars can be > old chars to be replaced Multiple occurrences of old chars will be replaced with only the first new char Multiple occurrences of old chars will be replaced with every new char
  48. 48. Reverse(arg1) • This function will reverse a string or a number
  49. 49. DATE TYPE ● STANDARD date formats supported in ORACLE are ● DD-MON-YY ● DD-MON-YYYY ● Only those formats can be used for storing date values in any column declared as a date type ● Any other format other than the above depicted ones will be treated as a char type and not as a date type
  50. 50. Date and time functions • Sysdate – This function returns the system date and this function will not accept any arguments – select sysdate from dept; • Add_months(arg1, arg2) – This function will return a date succeeding or preceding the no of months from the date specified in arg1 – Arg1 is the date type – Arg2 is the number type(no of months) – select add_months(sysdate, 120) from dept
  51. 51. Contd.. • Months_between(arg1, ag2) – This function will return the no of months between 2 dates – Arg1 and arg2 are of date types – select round(months_between(sysdate, '13-jan-83')/12) || ' years' from dept – select ename, round(months_between(sysdate, hiredate)/12) || ' years' from emp • Last_day(arg1) – This function will return the last day of a date specified in arg1 – select last_day('02-feb-13') from dept • Next_day(arg1, arg2) – This function will return the date on the coming day of the week – Arg1 is the start date – Arg2 is the day of the week(mon – sun) – select next_day(sysdate, 'sat') from dept – select next_day(sysdate, 1) from dept
  52. 52. Contd.. • Arg2 in next_day function can also be of a number type ie from 1 to 7 which is from sun to sat • Current_timestamp – This function will return the system date and system time which does not accept any arguments – select current_timestamp from dept;
  53. 53. CONVERSION FUNCTIONS
  54. 54. DESCRIPTION • These functions are used for converting one type of data into another • To_char(arg1, arg2) – This function converts a date or a number type into a char type – Arg1 is the date or number value and arg2 is the format in which you want to represent that date or number value – Arg1 must and should be a • Function • Column name • Variable – And must not be a date constant but can be a number constant – User defined formats in arg2 must be enclosed in “ “
  55. 55. select to_char(sysdate, 'dd-mm-yyyy') from dual / 22-01-2013 select to_char(sysdate, 'year') from dual / Year is printed in words select to_char(sysdate, 'dy') from dual / Day : tue select ename, to_char(sal, '$99999.99') from emp1 / select to_char(1000, '9999.999') from dual / select to_char(hiredate, ' "you have joined on" dd-mm-yyyy') from emp1 /
  56. 56. To_date(arg1,arg2) • This function will convert a char type into a date type • Ag1 is the date value • Arg2 is the format of the date value in arg1 • Advantage with this function – User can supply any customized date format which can be converted into standard date format using this function
  57. 57. Extract() • This function will extract a part of the date from a given date • The return type of this function is a number • “Year”, “month” and “day” formats only must be used in this function and no other format is allowed – select extract(year from sysdate) from emp1 – select extract(month from sysdate) from emp1 – select extract(year from sysdate) - extract(year from hiredate) from emp1
  58. 58. Aggregate functions • Sum(a1) • Avg(a1) • Min(a1) • Max(a1) • Count(a1)
  59. 59. Description • Aggregate functions are multiple row functions because every aggregate function will return utmost 1 value for all the rows of a table • Number, string, date and time, conversion functions are single row functions because these functions return utmost 1 value for every row of a table • You can pass any type of data as an argument to max, min, count functions • Aggregate functions completely ignore NULL values
  60. 60. Real time applications with functions • select dname from dept where dname = initcap('accounts') • update emp1 set sal = sal + (sal*10/100) where extract(year from hiredate) = 1987
  61. 61. Clauses in select statement
  62. 62. Group by and having clauses • This clause is used to group the data according to a criteria using a column • Syntax – Select <col name>, <aggregate function> from <table name> group by <col name>; – Eg : select deptno, max(sal) from emp group by deptno • Any column identified in the group by clause need not appear in the select clause(select max(Sal) from emp group by deptno). But any column identified in the select clause must and should appear in the group by clause(select ename, max(sal) from emp group by deptno → error) • Group by clause used on a column will by default display the data in ascending order • Group by clause by default will eliminate duplicates
  63. 63. Contd.. • Aggregate function cannot be used in WHERE clause. Hence we should use having clause for that purpose – select deptno, max(sal) from emp group by deptno cl having max(Sal) >= 3000 • Group by and having clauses can be used without aggregate functions
  64. 64. Order by clause • This clause is used for sorting data in a column in ascending or descending order • Syntax – Select <col name> from <table name> order by <col name> [asc]/desc – select * from emp order by ename desc – select ename, job, hiredate from emp order by 2 desc – select ename emp_name from emp order by emp_name desc
  65. 65. • Alias name can be used in the order by clause • Number in the order by clause signifies the position of the column in the select clause • Order of clauses – select deptno, max(sal) from emp where sal >= 3000 group by deptno having max(Sal) >= 3000 order by deptno desc – /
  66. 66. CONSTRAINTS
  67. 67. DESCRIPTION • CONSTRAINT is a limitation or restriction to be imposed on any column of a table to validate data • When to impose constraints? – Constraints can be imposed either during the process of table creation or after creating a table • Constraint types – NOT NULL – UNIQUE – PRIMARY KEY – CHECK – DEFAULT(Default cannot be treated as a constraint by DBA) – key
  68. 68. HOW TO IMPOSE A CONSTRAINT DURING THE PROCESS OF TABLE CREATION? • Create table <table name>(<col name> <data type> [constraint <constraint name>] constraint type); • Providing a name to the constraint is optional. Ie if you do not provide a name to the constraint then by default, the system will provide it’s own name in the format SYS_<number> • Constraint name is provided for disabling or deleting a constraint • SYS is the user name for SYSDBA
  69. 69. Not null • This constraint is imposed to obscure the entry of null values into a column of a table – create table testnull(sno number constraint tab1_nn not null) – create table testnull2(sno number not null, sname varchar2(20) not null) • Command for tracking names of constraints – select constraint_name, table_name from user_constraints where table_name = upper('testnull1') • At run time, null value should be explicitly passed for number type and do not enter any value to enter NULL value for char type
  70. 70. Unique • This constraint when imposed on any column of a table will not allow data in that column to be duplicated – create table testun(sno number unique) – create table testun1(sno number unique, age number unique) • One NULL value is never equal to another NULL value.
  71. 71. Primary key • This constraint is a combination of unique and not null • In a table on a max basis, you can impose only one physical primary key. But on a need basis, if you require to define 2 primary keys in 1 table, then explicitly impose a combination of UNIQUE and NOT NULL – Create table testun2(sno number unique not null) – create table pk(sno number primary key) – create table pk1(sno number unique not null, age number unique not null);
  72. 72. Check • This constraint is used to impose user defined or customized restrictions on any column of a table • Impose a restriction on a column in such a way that age must be > 18 years • Impose restriction on a column mbno in a table in such a way that mbno must exactly contain 10 digits • Impose restriction on a column mbno in a table in such a way that mbno must exactly contain 10 digits and mbno should start with 9 • Impose a restriction on a column dob in such a way that date must fall on either mon or wed or fri
  73. 73. Queries • create table che1(age number check(age > 18)) • create table ch2(mbno number check(length(mbno) = 10)) • create table ch3(mbno number, check((length(mbno) = 10) and (substr(mbno, 1, 1) = 9))) • create table ch4(dob date check(to_char(dob, 'dy') in('mon', 'wed', 'fri')))
  74. 74. Default • This is a restriction which is used to over ride NULL value with a DEFAULT value • Default value will be inserted whenever you are not entering data into any column of a table. But default value will not be inserted whenever you are explictly passing a NULL value • Default keyword should be used in INSERT command if the table has only 1 column which had been defined under default restriction – create table def1(sno number, sname varchar2(20) default 'Ravi Shankar') – create table def2(sno number, dob date default sysdate) – insert into def4 values(default);
  75. 75. Add constraints after creating a table • alter table addcons add primary key(sno); • alter table cons3 add unique(sno); • alter table cons3 add check(sno > 101); • alter table cons4 modify(sno number not null); • alter table cons5 modify(age number default 18);
  76. 76. Table and col level constraints • Table level constraints only can be added using ADD attribute of ALTER command and not Column level constraints • Primary key, check and unique are called as table level constraints because they can be added using ADD attribute of ALTER command • Not null and default are column level constraints and cannot be added using ADD attribute of ALTER command • Not null and default constraints can be logically added using MODIFY attribute of ALTER command
  77. 77. Description of table and column level constraints • Table level constraint – If the constraint type and column definition can appear at different places in the same table then that constraint is referred to as a table level constraint – create table cons6(cno number, cname varchar2(20), primary key(cno)) – create table cons7(sno number, sname varchar2(20), unique(sno)); – create table cons8(sno number, age number, check(sno > 101));
  78. 78. Contd.. • Column level constraint – Constraint definition and column definition must appear at the same place in the same table • The advantage with a table level constraint is that you can define a COMPOSITE PRIMARY KEY only by using table level constraints • Composite primary key – When a primary key can be imposed on multiple columns in the same table then that primary key is called as a composite primary key – create table cons8_edge(cid number, ano number, primary key(cid, ano))
  79. 79. Constraint operations • Delete a constraint without deleting a column from a table – alter table cons9 drop constraint SYS_C005256; – alter table cons9 drop primary key; – You cannot delete any other constraint without a name except for primary key constraint • Rename a constraint – alter table cons13 rename constraint SYS_C005261 to pk_cons13; • Enable or disable primary key – alter table cons14 disable primary key – alter table cons14 enable primary key – alter table cons15 disable constraint SYS_C005263
  80. 80. Foreign key • This is a constraint used for establishing table relationships • 2 tables can be related if a common column is defined in both the tables • The common column should not be duplicated and should not contain NULL values in that table from which it is borrowed as a common column • Therefore a primary key column must be taken as a common column. Because primary key is a combination of UNIQUE and NOT NULL • The table from which a primary key column is taken as a common column is called as a Master Table. The other table is called as a transaction table. • Any table in which a foreign key column got reflected is called as a transaction table
  81. 81. Steps to implement a foreign key • Create a master table – create table master1(cno number primary key, cname varchar2(20)) • Create a transaction table – create table trans1(sno number primary key, sname varchar2(20), cno number references master1(cno)) • Deletion anamolies – You cannot delete data from the master table directly without deleting the data from the transaction table because the foreign key column is referring to the primary key column – In case you need to delete data from the master table directly then you should use a clause in the transaction table ON DELETE CASCADE
  82. 82. CONTD.. • On delete cascade – On deleting a row from the master table, the cascading or automatic effect of deletion is reflected on transaction table – create table master2(cno number primary key, cname varchar2(20)) – create table trans2(sno number primary key, sname varchar2(20), cno number references master2(cno) on delete cascade)
  83. 83. Contd.. • On delete set null – This clause should be used in the transaction table so that if you delete a row from the master table, the corresponding column value in the transaction table will be updated to NULL without deleting a row and a column from that table
  84. 84. Contd.. • Add foreign key after creating a table – alter table trans4 add foreign key(cno) references master4(cno) on delete cascade; • In one transaction table, you can define more than 1 foreign key • Foreign key column must and should be defined as a primary key (logical or physical)or as a unique key in the master table • The names of the foreign key and primary key columns can be different but data type must be the same
  85. 85. JOINS • Joins is a technique of retrieving data from multiple tables by eliminating the cross product of rows among tables • Equi join – This type of join condition has to be defined whenever tables are related – = operator will be used to define a equi join • Display the ename and dname from emp and dept tables – select ename, dname from emp, dept where emp.deptno = dept.deptno • Display the ename and exp , dname of every emp – select ename, dname, extract(year from sysdate) - extract(year from hiredate)exp from emp, dept where emp.deptno = dept.deptno • Display the ename and dname of those emps whose sal is > 2000 – select ename, dname, sal from emp, dept where emp.deptno = dept.deptno and sal > 2000
  86. 86. Non equi join • This type of join condition will be defined whenever tables are not related • Between and operator can be used to define a NON EQUI JOIN • Display ename, sal and grade of every emp – select ename, sal, grade from emp, salgrade where sal between losal and hisal order by grade asc – select emp_name.ename as emp_name, sal, grad.grade as grad from emp emp_name, salgrade grad where sal between losal and hisal order by grad asc
  87. 87. Combination of equi and non equi joins • Display the ename, dname and grade of every emp – select ename, dname, grade from emp, dept, salgrade where emp.deptno = dept.deptno and sal between losal and hisal • To join N tables, we need to define N – 1 join conditions
  88. 88. Alias names • This is a temporary name that is used for a column for display purpose • Syntax – Select <col name> <alias name> from <table name>; • select ename emp_name from emp • select ename "emp_name" from emp • Alias name and col name by default will be displayed in upper case. If you want the same case to be displayed then alias name should be provided in “ “
  89. 89. Contd.. • Define joins using alias names – select emp_name.ename as emp_name, dept_name.dname as dept_name from emp emp_name, dept dept_name where emp_name.deptno = dept_name.deptno • As keyword should be used to differentiate between the alias used for join and display purpose. As keyword is optional and is used only for readability • Display the ename, dname and deptno from emp and dept tables – select ename, dname, emp.deptno from emp, dept where emp.deptno = dept.deptno
  90. 90. Outer join • This type of join condition has to be defined whenever you want to select all rows from 1 table and matching row from the other table • + symbol has to be used adjacent to that table from where yu are selecting matching rows • When you use + symbol on left side it is called as LEFT OUTER JOIN • When you use + symbol on RIGHT side it is called as RIGHT OUTER JOIN – select ename ,dept.deptno, dname from emp, dept where emp.deptno(+) = dept.deptno – select ename, dname from emp, dept where emp.deptno = dept.deptno(+)
  91. 91. Self join • Joining a table to itself – Manager_name is not a pre defined column of emp table – Manager_name can be logically obtained from emp name – Manager id of an emp must match with the empid of the manager – select emp_name.ename as emp_name, manager_name.ename as manager_name from emp emp_name, emp manager_name where emp_name.mgr = manager_name.empno – /
  92. 92. SUB QUERIES
  93. 93. Description • It is a query within some other query • Display the details of those emps who are getting a sal > smith – select * from emp where sal > (select sal from emp where ename = upper('smith')) • Display the details of those emps whose experience is > than experience of ford – select ename, extract(year from sysdate) - extract(year from hiredate) exp from emp where (extract(year from sysdate) - extract(year from hiredate)) > (select extract(year from sysdate) - extract(year from hiredate) from emp where ename = upper('ford')) • Update the sal of allen to the same sal as that of smith – update emp set sal = (select sal from emp where ename = upper('smith')) where ename = upper('allen')
  94. 94. Advantages with sub queries • You can write a sub query to eliminate the problem encountered using GROUP BY CLAUSE • You can create table copies and views using sub queries
  95. 95. Advantage 1 • Display the max(sal) from every department and also the name of that emp who is getting the max(sal) – select ename, sal, deptno from emp where sal in(select max(sal) from emp group by deptno)
  96. 96. Table copies • Create a table copy of emp table – create table empcopy as select * from emp • Create a table copy without copying data from the base table – create table empcopy1 as select * from emp where 1 = 2 • Copy data from base table into table copy – insert into empcopy1(select * from emp);
  97. 97. Table copies • In table copies, constraints are not copied from the base table • Updations made on a table copy are not reflected on the base table
  98. 98. View • View is a virtual table which will be logically identified as an image of the base table Emp table oracleUser View1 Update sal
  99. 99. Views contd.. • View is called as a virtual table because you cannot store data in a view • Syntax for creating a view – Create view <view name> as <select statement>; • Updations made on a table or on a view are reflected on the other data base object • Create a view without a base table – create force view v2_abc as select * from abc • When you delete a table on which a view is dependent then that view will become invalidated
  100. 100. Views contd… • Create a view which will contain max sal from every dept – create view v4_emp as select deptno, max(sal) max_sal from emp group by deptno – Alias name should be used because view is created only for pre defined columns in a table and you cannot create a view with a column which is not existing in the table – YView created with aggregate function is a read only view – View created with any other type of function is not a read only view but you cannot make any updations on virtual columns(col existing in view but not in table) in that view
  101. 101. Views contd.. • With check option – This clause is used to define a condition in the where clause of the select statement in a view definition as a constraint • create view v9_emp as select empno, ename, sal from emp where sal > 2000 with check option • Read only view • create view v11_emp as select empno, sal from emp with read only • Create a view on a view – Create view <view name 2> as select <col> from <view name 1> • Delete a view – drop view v13_emp;
  102. 102. Table copy View updations made on a table copy are not reflected on the base table Updations made on a view are reflected on the base table Constraints are not copied into table copy Constraints are copied into table copy Physical Virtual
  103. 103. Oracle Data base Tables Views Synonyms Indexes Sequences Constraints Procedures Functions Packag Triggers Varrays Clusters
  104. 104. • Views can be used to track details about different types of data base objects which are stored in the data dictionary of the data base
  105. 105. Synonyms • This is a permanent alias name through which you can access any data base object • SYNTAX for creating a synonym ● Create synonym <syn name> for [<user name>] . <table name>; – create synonym d1 for empcopy; • Why to create synonyms? – Synonyms can be used to access a table if the table had been created with a very long name
  106. 106. Sequences • Sequence is a data base object which automatically generates numbers in a progression • Syntax for creating a sequence – Create sequence <sequence name> [<start with> value] [minvalue <value>] [ increment by <value>] [<maxvalue> value>] [cycle cache <value>]; • Attributes of sequence object – Nextval : this is an attribute which will be generating the next value from the current value – Currval : Generates the current value of a sequence • Select <sequence name>.<nextval> from <table name>; • Select <sequence name>.<currval> from <table name>; • Current value of a sequence object will be stored in the cache memory
  107. 107. Contd… • Modify max value – alter sequence s3 maxvalue 30 – Maxvalue must be >= current value • Start with value cannot be generated for more than once and suceeding the generation of the max value if you want to get back to the start with value, you should use a clause minvalue • Cycle cache value = ((maxvalue) – (minvalue))/2 • Remove cycle cache – alter sequence s8 nocycle • Add cycle cache – alter sequence s8 cycle cache 25 • Command for tracking sequence details – select sequence_name, min_value, max_value from user_sequences where sequence_name = 'S8';
  108. 108. Contd.. • Min value must always be <= start with value • Add minvalue – alter sequence s11 minvalue 2; – Minvalue must always be <= current value ie once a sequence object is created, the default min value will be the start with value PROVIDED you did not define any start with value • Add increment by value – alter sequence s13 increment by 20;
  109. 109. Use sequence in table
  110. 110. PL/SQL(PROCEDURAL LANGUAGE OR SQL )
  111. 111. Description • Any language in which you can write programs is called as a procedural language • Integrating SQL in a procedural language is called as PL/SQL • Why to integrate SQL in a procedural language? – SQL is a non procedural query language which at times is a disadvantage to a data base programmer due to which he cannot implement the data base flexibly because of the following cited reasons
  112. 112. Disadvantages with SQL • SQL queries are not reusable because they cannot be stored in a data base • SQL queries cannot abstract the data base object from outside world • SQL queries degrade the performance of a data base Emp User Insert 20 rows HDD
  113. 113. Contd.. • Hence because of the the above cited flaws in SQL, SQL has to be integrated in a procedural language • We can integrate SQL in a procedural language by writing a program • Programs can be written by using ANONYMOUS BLOCKS • BLOCK is a unit which combines a procedural construct (variables, conditions, loops etc)with SQL statement
  114. 114. Structure of a BLOCK Declare <local variables >; Begin <variable intializations>; <conditional statements>; <loop statements>; <SQL statements>; <output statements>; Exception when <exception type> then raise_application_error(errno, message); End;
  115. 115. Output statement • Dbms_output.put_line(message/variable/func tion); • Dbms_output is a package and put_line is a procedure
  116. 116. Variables • Declare variables – <variable name> <data type>; – SQL data types can be used to declare variables in PL/SQL – := is an assignment operator and = is a comparison operator • Default value for a local variable in a block is NULL • Declare variable as not null – <variable> <data type> not null := <value>; – A variable declared as not null must be intialized to a value only at the place of declaration – When you declare a variable as not null, explicitly you cannot pass a null value to be stored in that variable
  117. 117. Contd.. • Constant variable – Any variable for which a value cannot be modified is called as a constant variable – <variable> constant <data type> := <value>; • n constant number := 20; • Commonality in not null and constant variables – Not null and constant variables have to be initialized to some value only at the place of declaration • Difference between constant and not null variables – Not null variables can be modified – Constant variables cannot be modified • Default variable – <variable> <data type> default <value>;
  118. 118. Vars contd.. • Variables declared in the declaration section are always having a scope of LOCAL ie they are identified as LOCAL variables
  119. 119. If else -- print max of 2 nos declare n1 number := &num1; n2 number := &num2; begin if(n1 > n2) then dbms_output.put_line('max n1 = ' || n1); else dbms_output.put_line('max n2 = ' || n2); end if; end;
  120. 120. Nested if else -- print max of 3 nos declare n1 number := &num1; n2 number := &num2; n3 number := &num3; begin if(n1 > n2 and n1 > n3)then dbms_output.put_line('max n1 = ' || n1); elsif(n2 > n1 and n2 > n3) then dbms_output.put_line('max n2 = ' || n2); else dbms_output.put_line('max n3 = ' || n3); end if; end;
  121. 121. Syntax for case statement Case when expression 1 then Statement 1 when expression 2 then Statement 2 When expression 3 then Statement 3 End case;
  122. 122. loops (spec to oracle) Loops are used for executing a piece of code for more than 1 time eg : reading 10 rows from a file, Insert multiplication tables in a file etc 3 types of loops 1. while loop 2. do while loop 3. for loop syntax for defining a while loop while(expression) loop statement end loop;
  123. 123. ● Until the boolean value of the expression is true, the code within the body of while loop would execute ● WHILE loop will terminate when the boolean value in the expression is false
  124. 124. Case statement declare • text varchar2(20) := 'welcome to cmc'; • choice number := &choice; • begin • case when choice = 1 then • text := upper(text); • when choice = 2 then • text := initcap(text); • when choice = 3 then • text := lpad(text, length(text) + 10, '@'); • end case; • dbms_output.put_line('choice = ' || choice || ' and formatted text = ' || text); • end;
  125. 125. Contd.. • When you compare a null value with a variable in a condition of a IF statement then the condition will always evaluate to FALSE and the ELSE part will get executed • Cases can be duplicated and at any point of program execution, max only 1 case will be executed and in case of duplicate cases, first occurrence of the duplicated case would be executed • Case constant can be a decimal value • Operators can also be used in case statements
  126. 126. LOOPS
  127. 127. While loop -- print nos from 1 to 20 using while loop declare n1 number := 1; begin while(n1 <= 20) loop dbms_output.put_line('n1 = ' || n1); n1 := n1 + 1; end loop; end;
  128. 128. Do while loop ● Syntax for defining a do while loop loop ● statements
  129. 129. Do while loop -- print nos from 1 to 20 using do while loop declare n1 number := 1; begin loop dbms_output.put_line('n1 = ' || n1); n1 := n1 + 1; exit when n1 > 20; end loop; end;
  130. 130. For loop -- print nos from 1 to 20 using for loop begin for n1 in 1..20 loop dbms_output.put_line('n1 = ' || n1); end loop; end; /
  131. 131. For loop • Loop variable need not be declared, initialized and incremented in a FOR loop • Using a for loop, we can print numbers in a reverse order without the need for decrementing a variable value • User defined increment value cannot be identified in a for loop
  132. 132. While loop Do while loop Loop will terminate when condition is false Loop will terminate when the condition is true Condition Negation of condition Differences among while and do while loops
  133. 133. %type • This is an attribute used for declaring variables in a block ie this attribute must be used whenever you are declaring variables to belong to the same type as that of a column in a table • Syntax for using %type – <variable name> <table name> . <colname> % type • The advantage of using this attribute is that changes made to the col size and type are automatically reflected in a variable of a block Data type
  134. 134. Example declare eno emp.empno%type; name emp.ename%type; begin eno := &empno; select ename into name from emp where empno = eno; dbms_output.put_line('name = ' || name); end;
  135. 135. INTO operator • This operator has to be used for copying data from a column into a variable • Syntax for using this opeartor – Select <col name 1> into <variable 1> from <table name> where <col name 2> = <variable 2>; • Variable 1 is a variable that had been declared either for displaying a value or calculating a value for which already some value is available in a column of the table • Variable 2 is a variable that is being used as an input variable • Select command in a block is only used for copying data from a column into a variable and cannot be used for displaying data from a block
  136. 136. CURSORS
  137. 137. CODE declare name emp.ename%type; begin loop select ename into name from emp; dbms_output.put_line(name); exit when name is null; end loop; end;
  138. 138. PROBLEM WITH THE CODE • In the above code snippet, INTO operator cannot be used for copying multiple values from a column into a variable • Hence we cannot use a block alone for displaying multiple rows • Therefore we have to define CURSORS in a block for displaying multiple rows
  139. 139. Introduction to cursors • Cursor is a private SQL area used for fetching the data from a table row wise. For every SQL statement issued by the user, a cursor will be created for that statement by the data base • Cursor is private because user cannot create a cursor • Cursor is a SQL area because cursor will be created by the data base only for SQL QUERIES issued by the user at run time
  140. 140. EMP TABLE USER Select ename from emp Implicit Cursor Pointer to 1st Row of a table Fetch row into cursor HOST VARIABLES Block Explicit Cursor
  141. 141. Define explicit cursor • Declare the cursor – Cursor <cursor name> is <select statement>; • Open the cursor – Open <cursor name>; • Fetch the data from a cursor into a local variable – Fetch <cursor name> into <local variable>; • Close the cursor – Close <cursor name>;
  142. 142. Steps usage • Open a cursor – Cursor has to be opened to execute the query identified in the cursor declaration . Since opening a cursor enables a query to be executed, cursor has to be opened in the BEGIN section of a block • Copy data from a cursor into a variable – Cursor is not a variable and user cannot directly access a cursor. Hence data from a cursor has to be copied into a variable
  143. 143. Attributes of a cursor • Syntax for using cursor attributes – <cursor name> %attribute • %notfound – This attribute is used to verify whether data is available in a cursor or not – This attribute will always return a BOOLEAN value. Default boolean value for this attribute is always FALSE • %rowcount – This attribute will validate a cursor with respect to the no of rows available in a cursor ie using this attribute you can determine the no of rows available in a cursor • %rowtype – This attribute is used to declare 1 variable for all the columns of a table
  144. 144. Contd.. • You cannot use a WHILE loop for using the attributes %notfound and %found because the default boolean values for these attributes are always false • %rowcount can be used to display the no of rows fetched from a cursor into a variable • Variable declared as %rowtype is only used to access all the columns of a table and that variable cannot store the data from all the columns of a table. That variable is called as a record set • Local variables in a cursor have to be declared for – Display purpose – Calculation purpose
  145. 145. Advantages with cursor • Cursor can be defined in a procedure or a function • Select query can be declared in a cursor • Procedure or function can be stored in a data base • Hence you can re use SELECT statement using a procedure or a function through a cursor
  146. 146. EXCEPTION HANDLING MECHANISMS
  147. 147. Description • Exception is a mechanism for handling run time errors generated in a code • Run time errors are generated because of – Invalid inputs given by the user – Incorrect logic of the program • Exceptions can be raised using exception type. Exception type is a variable which is of type exception • 2 types of exceptions can be used in Oracle Data base – System defined exception types – User defined exception types
  148. 148. Contd… • System defined exception types are always used to only handle run time errors and you cannot use these exception types to throw run time errors • If you want to create and throw a run time error then we need to make use of user defined exceptions • System defined exceptions – zero_divide : This exception type has to be used whenever you want to handle a run time error which will be generated because of dividing a number by 0 – No_data_found : This exception type has to be used whenever the code is throwing a run time error due to non availability of the data in a table – Too_many_rows : This exception type has to be used whenever INTO operator is attempting to copy more than 1 value from a column into a variable
  149. 149. Raise_application_error(errno, message) • This is a procedure which can be called or used to display a message like a error message • This procedure will accept 2 parameters. First parameter is the error number and second parameter is a variable or function or text • Error number must be provided as a first argument because. In oracle, every RUN TIME and COMPILE TIME errors is associated with a number • Since the message to be rendered by this procedure is user defined, accordingly the error number must also be user defined • Even though the error number is user defined, it must be within the range -20001 to -20990
  150. 150. Contd… • This procedure can also be used in the BEGIN section of a block. In that case, exception section is not required for using this procedure • But exception section would be mandatory to be used in case of user defined exceptions and exception section is mandatory to be used whenever you want to handle a specific run time error generated by a system
  151. 151. Zero_divide declare n1 number := &n1; n2 number := &n2; begin dbms_output.put_line(n1||'/'||n2||'='|| (n1/n2)); exception when zero_divide then dbms_output.put_line('Denominator must not be 0...'); Exception type
  152. 152. NO DATA FOUND --write a block for reading eno and display the name of an emp declare eno emp.empno%type := &empno; name emp.ename%type; begin select ename into name from emp where empno = eno; dbms_output.put_line(name||' is the name
  153. 153. Too many rows declare name emp.ename%type; begin select ename into name from emp; dbms_output.put_line(name); exception when too_many_rows then raise_application_error(-20001, 'INTO OPERATOR CAN COPY MAX ONLY 1 ROW FROM A COL INTO A VAR...'); End;
  154. 154. User defined exceptions • These exception types are used and defined for throwing user defined run time errors • Steps to define a user defined exception – Declare the exception type in the declaration section of a block • <exception variable> exception; – Raise the exception using a if condition If(condition) then statements; Else raise <exception variable>; – Handle the exception using the exception section • Exception <exception var> then
  155. 155. Contd… • Exception type has to be declared so that the exception type can be used in the exception section of a block • Exception has to be raised for branching the control to the exception section of a block to throw the run time error • You cannot handle multiple exceptions from a block. In case if you want to handle multiple exceptions then define them in a procedure and call those procedures from a block
  156. 156. Example 1 -- write a block for adding 2 numbers. add those numbers if they are negative else do not add them declare n1 number := &num1; n2 number := &num2; res number; inv_no exception; --exception var begin if(n1 < 0 and n2 < 0) then res := n1 + n2; dbms_output.put_line(n1||' + '||n2||' = '||res); else raise inv_no; exception when inv_no then raise_application_error(-20003, n1||' or ' || n2 || ' is positive...');
  157. 157. Example 2 --create table testexc1(dob date, age number) declare dob testexc1.dob%type := '&dob'; age testexc1.age%type; inv_age exception; begin age := extract(year from sysdate) - extract(year from dob); if(age > 18) then insert into testexc1 values(dob, age); dbms_output.put_line(dob||' and ' ||age||' got inserted into testexc1 table...'); else raise inv_age; end if; exception when inv_age then raise_application_error(-20001, 'age = '||age||' < 18 years because you were born on '|| dob);
  158. 158. Can you handle a system defined run time error using a user defined exception? • If you want to handle a system defined run time error using a user defined exception type then you need to call the following procedure – Pragma exception_init(exception type, error no); • Exception type is a user defined exception type and error no is a system generated error number • This procedure has to be called in the DECLARE section of a block
  159. 159. Example 1 • -- write a block for inserting empno into emp table • declare • eno emp.empno%type := $empno; • dup_eno exception; • pragma exception_init(dup_eno, -00001); • begin • insert into emp(empno) values(eno); • dbms_output.put_line(eno||' got inserted into emp table...'); • exception when dup_eno then • raise_application_error(-20001, eno||' already existing in emp table...'); • end; •
  160. 160. Functions • Functions are used to store a cursor or an exception in a data base because functions themselves once compiled are stored permanently in a data base • If you want to store a cursor or an exception in a function, we cannot make use of system defined functions. Hence we need to define a user defined function for that purpose • Therefore we can make use of a function for code reusability because a block cannot be re usable for it cannot be stored in a data base
  161. 161. Syntax for defining or creating a function Create [or replace] function <function name(args)> return <data type> is <return var> <data type>; Begin Statements; return <return variable>; End [<function name>]; Function Prototype Or header Or decalartion Function defn If you do not use replace keyword then the Function can be compiled for max only 1 time ie Re compilation of the function is not possible
  162. 162. Call a function • Select <function name(args)> from <table name>; – select fun1(10,20) from dept;
  163. 163. Functions return value • Function can be defined with 0 parameters and a return variable of a function can be initialized to some value in case you are defining a function with 0 parameters. Do not use () if you are defining a function and calling it with 0 parameters • You can define a function with no return variable ie you cannot define a function in such a way that it is not returning any value. But you can define a function in such a way that no return variable had been declared. Do not use ; at the end of the function declaration if you are defining a function with no return variable • When you do not specify any size for varchar2 which is an argument type, you cannot specify any size for the return type. But a size has to be specified for varchar2 if it is a type of a return variable
  164. 164. Contd.. • You cannot define a size for varchar2 if it is a return type. If size for varchar2 as a return type cannot be specified then you cannot and should not specify a size for varchar2 as argument type • You can define a loop in a function. But that function will max return only 1 value which is the initial value assigned to a variable
  165. 165. Varchar2 type as par, return types ● When a return var is declared of type varchar2 then size has to be specified for that return var ● Size should not be provided for varchar2 if it is a return type ● Size should not be provided for varchar2 if it is a par type
  166. 166. Advantages with functions • Functions abstract the implementation from the outside world • Functions reduce the complexity of implementing the application • Functions can be re usable in a block • Whenever you are defining a function with INSERT or UPDATE or DELETE commands then the function cannot be called from a SELECT statement. Instead the function has to be called from a block which is an advantage with a block to call a function
  167. 167. Disadvantages with functions • You can define a cursor in a function. But that function will return max only 1 value from the first row of that table. Because functions max return only 1 value and cursor default position if the first row ie functions max return only 1 value which is the primary disadvantage
  168. 168. Command for tracking functions in a data base • select text from user_source where name like 'FUN %‘ – The above command will display the code written for every function – User_source is a view of the data dictionary which is used to track the details of functions, procedures and packages
  169. 169. Procedures Function Procedure Function returns 1 value programmatically and logically Procedure cannot return a value programmatically. But it can return more than 1 value logically Function can be called from a procedure, function and a block Procedure cannot be called from a function but can be called from a block or a procedure Cursor defined in a function can fetch utmost only 1 row Cursor defined in a procedure can fetch multiple rows Functions accept only IN parameters Procedures accept IN, OUT and IN OUT parameters
  170. 170. • You cannot call a procedure from a function because procedure cannot programmatically return a value. You can call a function from a procedure because function can return a value programmatically and that return value can be used anywhere within the procedure • You cannot assign a procedure to a variable because a procedure cannot return a value
  171. 171. Parameter types • IN – This parameter type is passed as an argument to a function or a procedure • OUT – This a parameter type for which a value will be returned by the procedure – Local variables are used to display values from a procedure logically . But they cannot be qualified as OUT parameters
  172. 172. Contd… • OUT parameters are not identified by a data base. Hence we have to register an OUT parameter with the data base. • Step 1 : Declare a host variable which is of the same type as that of the OUT parameter. The variable is called as HOST variable because, it should be declared in a data base and not in a BLOCK or PROCEDURE or FUNCTION – SQL> VAR <Variable name> <data type> • HOST variable is declared so that the return value of the procedure can be stored in that variable • Step 2 : Use that variable as a bind variable in the procedure call – Exec <procedure name>(<in1>, <in2>,……, :<host variable>); – If a variable is binded with the procedure call then that variable is called as a bind variable – Variable has to be binded in order to store the return value of the procedure in that variable
  173. 173. Contd.. • The advantage with OUT parameters is that you can re use OUT parameters in multiple procedures because you are registering an OUT parameter as a HOST variable and HOST variable is a variable declared in a data base. • Hence that variable can be passed as a BIND variable in multiple procedures which is not possible with LOCAL variables • Name of the HOST variable can be different from that of the name of an OUT parameter. Data types can also differ but they should be compatible
  174. 174. IN OUT parameters • If a parameter value that is passed as a IN parameter needs t be modified within the procedure then that parameter can be declared as IN OUT parameter • See the next slide to USE IN OUT parameters
  175. 175. PACKAGES
  176. 176. Description • Package is a collection of procedures and functions, variables • Why to define or create packages? – Packages are created for resolving the name conflicts among functions and procedures – Packages can be used to aggregate the functionalities of functions and procedures into a single unit so that you can just remember the name of the package instead of remembering the names of all functions and procedures – Procedure created for 1 user cannot be publicly accessible from the other user privileges. But a package can be publicly accessible from every user privilege
  177. 177. Eno number Ename varchar2(20) Hiredate date Basic number Da number Hra number Cca number Gross number Netsal number Procedure for Inserting data into the table Function DA Function Gross Function Netsal Function HRA Package
  178. 178. Java program To open an account in a bank Customer Account Data base Procedure to Insert account details Call procedure SCOTT CREATE No of programmers are 20 Write program
  179. 179. How to implement packages in ORACLE? • STEP 1 : We have to create a package specification – Package specification can be thought of as a prototype for defining a package ie functions and procedures will be declared in the package specification and will not be defined – Return variable for a function will not be declared in a package specification because you are only declaring the function and not defining it • STEP 2 : create a package body – Package body is used for defining the procedures and functions declared in the package specification
  180. 180. Syntax for defining a package specification Create [or replace ] package <package name> is Function <function name(args)> return <data type>; Procedure <procedure name(args)>; <variable_spec> <data type>; End;
  181. 181. Package body Create [or replace> package body <package name> is <variable_body> <data type>; function <function name(args)> return <data type> is <variable> <data type>; Begin statements; return <variable>; End; Procedure <procedure name(args)> is Begin statements; End; End;
  182. 182. Members visibility in a package • Variable or function or procedure declared in a package specification by default is having a public visibility ie that member can be accessed from outside the package specification • Member visibility in a package body is private ie that member cannot be accessible from outside the package • When you delete a package specification, by default even the package body will be deleted. If you delete a package body then the package specification by default will not be deleted
  183. 183. TRIGGERS
  184. 184. Description • TRIGGER is an event which is fired implicitly whenever a DDL or a DML transaction takes place in a data base • How to create a trigger? Create [or replace] trigger <trigger name> before / after insert/update/delete on <table name> [of <col name>] for each row Begin Statements End
  185. 185. EMP DBA Insert Rows only on SAT or SUN PROCEDURE Insert Data into Emp table on Sat or sun User Callprocedure ErrorMon to fri Block Insert Exception INSERT COMMANDANY DAY
  186. 186. NORMALIZATION Trigger syntax ● before/after : This is called as trigger timing and is used to tell the trigger when to fire ● Insert/update/delete : They are called as triggering events ie the events will tell the trigger to fire for a spcific DB transaction ● For each row : It is called as a trigger type. Trigger type will tell the trigger so as to how many times it has to fire ● There are 2 types of triggers that can fire : ● Statement level trigger : this trigger will fire for 1 time for all the rows ● Row level trigger(for each row) : this trigger will fire for 1 time for 1 row
  187. 187. Normalization • The main goal of normalization is to reduce data redundancy in tables in a data base and it is recommended not to completely eliminate redundancy • What is data redundancy? – Data redundancy = data duplication + data inconsistency – Data in a data base will become redundant if data is becoming inconsistent because of duplication
  188. 188. Examine the table Sno Sname Phone no 10 Ravi shankar 100,200,300 20 James 101,201 30 Javed 202 40 Akhtar 50 Suresh 203 60 Styanedfra 204, 205
  189. 189. Contd.. • In the preceding table, At least 1 student is possessing more than 1 phone number. Hence for 1 row, we have to store multiple phone numbers in phone number column • But any proprietary data base will be deployed in such a way that in any cell of a table, you can store max only 1 value in order to eliminate the anomalies caused due to INSERT or UPDATE or DELETE • Deletion is a row wise operation. Hence one entire row will be deleted if you issue a delete command for deleting phone numbers of a student. • Hence the problem encountered using delete command can be solved using Update command. Ie if you update phone number 100 to null then only 1 phone number will be deleted . But update command will be functional if and only if there is only 1 value in any cell of a table
  190. 190. Contd.. • Insert command would also throw a problem in the future whenever you are inserting data into that table • Suppose you want to insert a row with sno = 60 for whom there are 2 mobile numbers and 3 columns in a table(sno, sname and phone number), we need to pass 4 values to the insert command which are identified as invalid no of arguments. Hence that row will not be inserted • Hence whenever you are storing data in that table in such a way that one column is accommodating multiple values for a particular row, then that column would be responsible for causing anomalies in INSERT, UPDATE and DELETE • Therefore the presence of multi valued attributes in a table are causing problems to INSERT, UPDATE and DELETE
  191. 191. Multi valued attributes • Multi valued attribute : When a column is storing multiple values for a particular row then that column is called as a multi valued attribute • In our example, phone no column can be qualified as multi valued attribute because this column is storing multiple phone numbers for a particular row • Multi valued attributes will be responsible for causing anomalies in INSERT, UPDATE and DELETE commands
  192. 192. Solutions to the problems faced due to multi valued attributes • Solution 1 : Ensure that phone number column is storing max only one phone number for every row Sno Sname Phone no 10 Ravi shankar 100 10 Ravi shankar 200 10 Ravi shankar 300 20 Javed 101 20 Javed 102 30 Akhtar NULL
  193. 193. Problem with solution1 • Sno column will be duplicated because of phone number column. • Hence sno column cannot be defined as a primary key. Sno column must be defined as a primary key because you need to uniquely identify a row using primary key • Phone no column cannot be defined as a primary key because it is not mandatory for every student to have a phone number. Hence a NULL value will be entered into that column for which a student is not possesing a phone number. Primary key cannot accept NULL values • Hence this solution is not effective to solve the problem of multi valued attributes
  194. 194. Solution 2 • Define one independent column for every phone number of a particular student Sno Sname Ph1 Ph2 Ph3 10 Ravi 100 200 300 20 James 101 102 30 Javed 103 40 Akhtar
  195. 195. Problem with solution 2 • This solution is not effective due to the following reasons – If you want to insert a row for which that student is possessing 7 phone numbers then you need to add 4 columns to the existing table. Hence for every data updation, I need to modify the table structure – In this connection, the user needs to directly access the table in a data base which may be a threat to the security and performance of the data base application
  196. 196. Solution 3 • Do not create phone number column or tell the student to maintain max only 1 phone number – This is a best solution from the programmar’s angle and a worst solution from the customers angle – Main goal of sotware development is to satisfy customer – Hence this solution is not acceptable ] • Hence the solution to solve the problem is that – one row should accommodate only 1 phone number – Sno should not be duplicated – Additional columns should not be added
  197. 197. Conclusion • Data redundancy in a table is caused due to the presence of multi valued attributes • Hence to reduce data redundancy, we need to normalize the table • You should not eliminate data redundancy because if data redundancy is totally eliminated then tables cannot be related
  198. 198. NORMALIZATION • This is a process of decomposing 1 table into multiple tables to reduce data redundancy • This process has to be implemented before creating tables in ORACLE data base • Hence this process is an activity of DATA BASE DESIGN • NORMALIZATION process can be identified to be implemented through the presence of MULTI VALUED ATTRIBUTES • MULTI VALUED ATTRIBUTES can be identified using ER DIAGRAMS
  199. 199. Sno Sname Major Cno Cname FN Fl Grade 101 RAVI JAVA 101 102 103 Cpp Oracle Ms.net Amir Amir venkat Hyd Hyd secbad A B A 102 Shankar MAIN FRAMES 104 105 SE MATHS Amir Satish Secbad Secbad A A Assumption : One faculty can max handle only 1 course Faculty name must be unique
  200. 200. First normal form • When you encounter multi valued attributes in a table then those attributes have to be identified in a second table ie 1 table has to be decomposed into 2 tables. 1 table comprising of single valued attributes and second table comprising of multi valued attributes – Table 1 = {sno, sname, major}  single valued attributes – Table 2 = {sno, cno, cname, FN, FL, grade}  multi valued attributes • Table 1 and Table 2 must be related because both these table initially belonged to only 1 table. 2 tables can be related by taking a primary key column as a common column • Sno and cno are primary key columns in the respective tables. But cno cannot be defined as a common column because it is a multi valued attribute. Hence sno must be defined as a common column
  201. 201. SNO CNO ble 2 = {sno, cno, cname, FN, FL, grade}  multi valued attributes CNAME FNFL Grade Table 3 Table 4` Full functional Dependency Partial functional Dependency
  202. 202. Second normal form • In 1 table if you encounter full functional and partial functional dependencies then that table has to be decomposed into 2 tables. 1 table comprising of full functional dependency and second table comprising of partial functional dependency • Table 3 = {sno, cno, grade}  full functional dependency • Table 4 = {cno, cname, FN, FL}  Partial functional dependency
  203. 203. THIRD NORMAL FORM • In table 4 cname and FN are directly dependent on CNO. But FL is indirectly dependent on CNO through FN ie FL is dependent on FN and CNO which is a transitive dependency • Hence decompose table 4 into 2 tables – Functional dependency – Transitive dependency • Table 5 ={ cno, cname, IN } • Table 6 = {IN, IL}
  204. 204. Updated tables • Table A = {sno, sname, major} • Table B = {sno, cno, grade} • Table C ={ cno, cname, IN } • Table D = {IN, IL}
  205. 205. Normal form Table 1 Table 2 First Single values attributes Multi Valued Attributes Second Full functional dependency Partial Functional Dependency Third Full functional dependency Transitive Dependency In any normal form 1 table will be deocmposed into 2 tables
  206. 206. ● Full functional dependency ● Non key column is totally dependent on a composite primary key. If the table has only 1 primary key then also it is called as a full functional dependency ● Partial functional dependency ● Non key column is partly depedent on a composite primary key ● Transitive dependency ● It is a dependency between non key columns
  207. 207. Basic terms ● Data ● Is A COLLECTION of RAW FACTS and FIGURES ● DATA BASE ● Data has to be stored in a data base for extracting useful infromation from it ● Data base can either be designed or data base can be borrowed from any body for storing data
  208. 208. ● Data base design must comply to the user's requirement ie any type of application that is to be developed requires a data base also to be designed ● Data base can be designed using FILES system . ● Data base can be designed using a FILE system but FILES have some disadvanatages ● Files cannot be distributed ● Data stored in a file is always redundant ie data can be duplicated in a file which will lead to data inconsistency and there is no provision in a C compiler to reduce or eliminate data redundancy which is the main problem with a file system ● In c compiler, you can store data only in text files and text files cannot be distributed or updated
  209. 209. ● Due to the disadvantages in file systems, programmars felt the need of using a data base that can offer security, re usability of data. With that thought in mind they felt that if data is stored in tables when compared to that of files the above requirements can be achieved ● Advantages with tables ● Data can be stored in any manner in a table ● Table can be implemented as a object but file cannot be implemented as an object ● Hence companies like IBM in the year 1992 developed it's own data base called as DB2 and this was possible for IBM because of the standard of tables in a data base
  210. 210. ● A language was required for maintaining DB2 data base. That language also was standardized by IBM in the same year referred to as SQL ● SQL is a non procedural 3rd generation query language . SQL was implemented by using some commands and was not implemented using programs ie SQL commands can be used for DB maintenance and operations and for that you need not write any programs ● Oracle company also started intergrating SQL into their DB products and happened to standardize a product namely ORACLE
  211. 211. Oracle ● Why the name oracle was standardized? ● Oracle is not only a data base but also a relational data base (Any data base that can be designed using tables is called as a relational data base) ● Oracle is a Relational Data Base Management System(till oracle 8) ie from oracle 9i onwards It was qualified as OBJECT RELATIONAL DATA BASE MANAGEMENT SYSTEM ● ORACLE is a data base server
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×