Introduction to DBMS A database management system (DBMS) consists of an interrelated data and a set of programs to access that data. The collection of data is usually referred to as database. The primary goal of a database is to provide an environment that is both convenient and efficient to use in retrieving and storing database information. Database systems are designed to manage large bodies of information. The management of data involves both the definition of structures for the storage of information and provision of mechanisms for the manipulation of information. In addition, the database system must provide for the safety of the information stored, despite system crashes or attempts at unauthorized access. If data is stored among several users, the system must avoid possible anomalous results. Database systems overcomes the problems faced in file-oriented system. The database system are controlled by the Database Administrator (DBA) Advantages of DBMS: Reduces Data redundancy (duplicity) and inconsistency of data. Provides data sharing facilities. Provides Data Integrity and Security. Provides Data Independence. Resolves concurrent access anomalies. DATA ABSTRACTION: A database management system provides users with an abstract view of data, i.e. the system hides certain details of how the data is stored and maintained. This concern has lead to the design of complex data structures for the representation of data in the database. Its complexity is hidden from the users through several levels of abstraction in order to simplify the interaction between the user and the system. 1 Physical Level: The lowest level of abstraction describes the data is actually stored in the database. Conceptual Level: The next-higher level of abstraction describes what data are actually stored in the database and the relationship that exists between them. This level is used by DBA, who must decide what information is to be kept in the database. View Level: The highest level of abstraction describes only a part of the entire database. DATA MODELS: A data model can be defined as a collection of tools for describing data and the relationship between them.Data models can be classified into the following groups. Object oriented logical models. Record based logical models. Physical data models. Object oriented logical models: They are used in describing data at the conceptual and view levels. Some of the widely known models are Entity Relationship model(ER model): is based on real world perception which consists of collection of basic objects called ‘Entities’ and ‘relationships’ among these objects. Object oriented model: is based on collection of objects. An object contains instance variables within the object. An object also contains bodies of code that operate on the object, called methods. Record based logical models: 2 They are used in describing data at the conceptual and view levels. As the database is structured in fixed-format records of several types, they are called as record based logical models. Some of the widely known models are: Relational model: represents data and relationships among data by a collection of tables, each of which has a number of columns with unique names. Network model: represents data by collection of records and relationships among data are represented by links which are viewed as pointers. Hierarchical model: represents data by collection of records, which are organized as trees rather than arbitrary graphs and relationships among data are represented by links which are viewed as pointers. Physical models: They are used in describing data at the lowest level. DATABASE FACILITIES: Two main types of facilities are provided by a DBMS: Data definition facility or Data definition language (DDL). Data manipulation or Data manipulation language (DML). Data definition language (DDL): A database scheme is specified by a set of definitions which are expressed by a special language called Data definition language (DDL).The result of compilation of DDL statements is a set of tables which are stored in a special file called Data Dictionary. The storage structures and access methods used by the database system are specified by a set of definitions in a special type of DDL called Data storage and definition language. The result of compilation of these definitions is a set of instructions to specify the implementation details of the database schemes which are usually hidden from others. Data manipulation language (DML): A Data manipulation language (DML) is a language that enables users to access or manipulate data efficiently. Data manipulation means 3 1. Retrieval of information stored in the database. 2. Insertion of new information into the database. 3. Deletion of information from the database. 4. Modification of data stored in the database. There two types of DMLS: 1. Procedural DMLs requires a user to specify what data is need and how it get it. 2. Non Procedural DMLs requires a user to specify what data is needed without specifying how to get it. Query is a statement requesting the retrieval of information. A portion of a DML that involves retrieval is called query language. STRUCTURE OF A DBMS: The major components of this system are Data definition language compiler: The DDL compiler converts data definition statements into a set of tables. These tables contain metadata concerning the database. Data Manager: The data manager is the central software component of the DBMS.Its function is to convert operation queries coming from query processor or indirectly or an application program from the user’s logical view to physical file system. The data manager is responsible for interfacing the file system. File Manager: It is responsible for the structure of files and managing the file space and also for locating the block containing required record, requesting this block from the disk manager, and transmitting the required record to the data manager. Disk manager: 4 The disk manager transfers the block containing the data requested by the file manager without the concern of physical characteristics of the underlying storage media. Query Processor: The query processor is used to interpret the online user’s query and covert it into an efficient series of operations in a form capable of being sent to the data manager for execution. It uses data dictionary to find the structure of the relevant portion of the database and uses this information in modifying the query. Data Files: Data files contain data portion of the database. Data Dictionary: A data dictionary is a file that contains metadata. i.e. data about data. This file is consulted before actual data is read or deleted in the database system. Different types of Keys: Attribute: An object or an entity is characterized by its properties or attributes, they can also be referred as field. 1. Primary key: An attribute to identify a record uniquely without allowing any null values to be entered into it is called Primary key. Ex: empno attribute in the employee table and deptno attribute in dept table. 2. Foreign key: An attribute which is a primary key in its own table and is used as a reference in another table is called foreign key. 3. Super Key: A primary key with a combination of other attributes for unique identification is called super key. In other words primary key is a minimum super key. Ex: Empno along with ename is super key. 4. Candidate Key: The super key for which no proper subset is a super key such a minimal super key is a candidate key. 5 Ex: Ename is a candidate key. STRUCTURED QUERY LANGUAGE(SQL) SQL is the official standard language used to access data held in the databases. SQL organizes data as tables , indexes , views etc. SQL is the tool for organizing , managing and retrieving data stored in the database. SQL provides various features like portability , client-server architecture ,dynamic data definition , multiple views of data etc. SQL Statements: SQL statements are divided into 1. Data Definition language(DDL) 2. Data Manipulation Language(DML) 3. Data Control Language (DCL) 4. Transaction Processing Language (TPL) 5. Data Retrieval Language (DRL) Data Definition Language (DDL): These statements define the structure of the database. DDL consists of create, alter and drop statements. Data Manipulation Language (DML): These statements are basically required to manipulate the records of the tabled consists of insert, delete, and update statements. Data Control Language (DCL): These statements are basically required to control the tables among several users by giving access or by taking back the access to the tables. DCL consists of grant and revoke statements. Transaction control language (TCL): These statements are basically related to various transactions like insert, delete, and update. Data retrieval language (DRL): These statements are basically required to retrieve the records for the table. DRL consists of select statements. Data types in SQL: 1.Varchar2(size): It is a variable length string with a max length of ‘size’ bytes. 2. Char (size): It specifies a fixed length character string. Max size is 255 3. Number (n): 6 It specifies integer type of data with max of n digits. 4.Number(p,s): It specifies floating number with p as total no of digits and specifies the number of digits to the right of decimal points. 5. Date: It specifies the date in DD-MM-YY format. Data definition language (DDL): Create statement: It is used to create and define a table. Syntax: Create table <table name> (<field-name1> <data type> [column constraints], <field-name2> <data type> [column constraints], . . . <field-name n> <data type> [column constraints]) ; Column constraints : 1. Primary Key: It will not allow null and duplicate values corresponding to that column. 2. Not Null : It will allow null values corresponding to that column 3. Unique: It will not allow duplicate values corresponding to that column. 4. Check: It will impose the constraints based on the condition being mentioned on the column. 5. Reference( foreign key): It will impose the constraints based on the condition being mentioned on the column 6. Reference (foreign key): It will refer to other column values that are acting as primary key in other table. 7. On delete cascade: It will delete the values in the column in one table, corresponding values in other table will be deleted automatically, and it will work only references only. Example 1: 7 Create a table employee with employee no as primary key, name field not be left empty, salary greater than 2000,job field not to be left empty,deptno is foreign key taken from dept table. Example 2: Create dept table with deptno as primary key and dept name as not null. SQL>Create table Dept (Deptno number(3) primary key, Dname varchar2(10) not null); Example 3: Create a customer table. SQL>Create table Customer (Cust_id number(5) primary key, First_name varcahr2(20) not null, Last_name varchar2(20) not null, Address varchar2(40), City varchar2(20), State varchar2(20), Phone_no number(9) unique); Table Level Constraints: Imposing constraints after declaring all the columns of the table, then we call it as table level constraints. Example 4: Create project table. SQL>Create table Project (Emp_id number(5), 8 Proj_id number(5), Payment number(8), Primary key(Emp_id,Proj_id); Create with Select: To create a table from taking the records from existing table. When creating a table based on existing table then it is going to transfer only not null constraint, other constraints will not be transferred. Example 1: SQL>Create table Emp As select Empno, Ename, Salary from Employee; Create with select using where clause: Example 2: Create a table empno containing the details in deptno 10 only SQL>Create table Empd As select * from Employee Where deptno=10; Alter Statement: It is used to alter the definition of a table in the database Syntax: Alter table<table_name> Add column_name data_type <column_constraint> [Modify column_name data_type <column_constraint>]; Add: is used when ever you want to add a new column to the table. Example 1: Adding Phno as a new field into Employee table SQL>Alter table Employee Add(Phno number(7)); Example 2: Adding empno as primary key to Emp table SQL>Alter table Emp Add(Primary key(empno)); 9 Modify: is used to change the size of the column of the same data type.Modify will not decrease the column size.Whenever it comes to increase in the size of column it is going to allow only when the field is empty. Example 1: Modify the salary field by increasing its size. SQL>Alter table Emp Modify(sal number(9,2)); Droping the Constraints: Example1: Dropping Primary key constraint we must see that no references are there from other tables. SQL>Alter table Emp Drop Primary key; Drop command: is used to drop the table. Syntax: Drop table<table_name>; Example 1: Dropping emp table. SQL>Drop table emp; Describe command: is used to display the structure of the table.Desc can also be used 10 Data Manipulation Language (DML): Insert command: is used to add rows(or records) to the table. The number and sequence should match that of columns in the table.If the number of data values is less, then specify the column names into which data is being entered. To insert null values, NULL can be used. Syntax: Insert into<table_name>values(datavalue_1,………..,datavalue_n); Insert into<table_name>(column_1,column_3) Values(datavalue_1,datavalue_3); Example 1: Insert 100th record into employee table. SQL>insert into employee Values(100,’James’,6000,’17-Mar-03’); Example 2: Inserting 101th record into employee table with salary and date Of joining as null values. SQL>Insert into employee Values(101,’James’,null,null); Example 3: Inserting 1001th record into employee table with only empno and name. SQL>Insert into employee(empno,ename) Values(1001,’John’); Insert with select: is used to transfer the data from one table to another table. Syntax: Insert into<table_name> Select <field_name_1>,……<field_name_n> from <table_name> Where<condition>; Example 1: SQL>Insert into emp Select empno,ename,sal from employee Where deptno=10; Delete Command: is used to delete the records from the specified table. Syntax: Delete <table_name> Where<condition>; 11 Example 1: Deleting the employee holding empno1001 SQL> Delete employee where empno = 1001; Example 2 : Delete all the records of the employee table SQL> Delete employee; Example 3: Delete the employees who are working as clerks. SQL> Delete employee where job =’clerk’ Update command: is used to modify the records of the table Syntax: Update <table_name> Set <field_name> = <value> , . . . Where <condition> ; Example1: Increase all the employees salary by Rs. 500 SQL> update employee set sal=sal+500; Example2: Give an increment of 20% salary and commission by 5%of salary SQL> update employee set sal = sal* 1.2, comm = (sal* 0.05) +comm; Example3: Promote the manager as director of the company SQL> update employee set job =’director ‘ where job= ‘manager’; Example4: Give an increment of 10% salary whose salary is less than Rs. 1000 SQL> update employee set sal = sal*1.1 where sal <1000; Transaction control language(TCL); The DML transactions will not be saved implicitly based on the following reasons. 12 1. Improper shut down 2. System crash 3. When working under SQL environment DML transactions will not saved. To handle DML transactions explicitly we require a set of commands which are commit, roll back and save point. Commit command: is used to save all the transactions up to the last command explicitly. SQL> insert into employee( empno, ename) values (200, ‘smith’); SQL> commit ; Roll back command: is used to undo the transactions up to the last commit. SQL> Rollback; Savepoint: is used to minimize roll back only to certain transactions Example: SQL> insert ……… SQL> savepoint ins; SQL> update ……. SQL> savepoint upd SQL> delete …. SQL> savepoint del; SQL> Rollback; SQL> commit; SQL> Rollback to del;(Once you commit and then give rollback, will remove all save points) Autocommit command: is used to make all DML transactions to save implicitly after the execution of the command. SQL> set autocommit on; SQL> set autocommit off; To see the status of autocommit we use show command. SQL> show autocommit; 13 Data Retrieval language(DRL); Select command: is used to retrieve the records from the table. Syntax: Select < field_name_1>, …….. , <field_name_n> from <table_name> where <condition> ; Example 1: To display the deptno,dname,loc. Example 2: To display all the employee details,who are working as manager. SQL>Select * from emp where job-‘manager’; Logical Operators: And Or Not Example 1: To display the employee information who are working in deptno 10 and salary greater than 2000. SQL>select * from emp Where deptno=10 and sal>2000; Example 2: To display the employee information who are working as manager corresponding to deptno 20. SQL>select * from emp Where job=’manager’ and depno=20; Example 3: To display the employee information who are working in deptno 10,20. 14 SQL>select * from emp Where deptno=10 or dept=20; Example 4: To display the employee information who are working as managers corresponding to deptno 10 as well as the employees who are receiving salary more than 2000 corresponding to deptno 20. SQL>select * from emp Where job=’manager’ and deptno=10; Special Operators: Is null In Between like is null: is used to check the null values corresponding to the column. Example 1: To display the employee information who are not receiving any commission. SQL>select * from emp Where comm Is null; Between: Whenever we want to frame the condition in the range of values then we use the between operator. Example1: To display the employee information whose salary is greater than 1000 and less than 2000. SQL>select * from emp Where sal between 1000 and 2000; Example 2: To display the employee information for those who are working for deptno 10 with their first alphabet of the name is coming in the range of ‘e’ to ‘j’. SQL>select * from emp Where deptno=10 and(ename between ‘E’ and ‘J’); In: When you have multiple conditions among which any one has to be selected we use in operator. 15 Example 1: To display the employee details who are working as managers ,clerks ,analyst. SQL>select * from emp Where job in(‘manager’,’clerk’,’analyst’); Example 2:To display the employee who are working in the deptno 10,20,30. SQL>select * from emp Where deptno in (10,20,30); Like: is used when you want to frame a condition based on a particular pattern, for which we need wild card characters, which are ‘%’ and ‘_’. ‘%’ is used to replace any no.of characters in the pattern. ‘_’ is used to replace only single characters in the pattern. Example 1: To display the employee details whose names are ending with ‘s’. SQL>select * from emp Where ename like’%s’; Example 2: To diplay the employee names have onlay 5 characters. SQL>select * from emp Where ename like’_____’; Example 3: To display the employee details whose name has ‘a’ as second character and ‘r’ as last character. SQL>select * from emp Where ename like’_a%r’; Special operators with not: Example1: To display the employee information who are receiving any commission. SQL>select * from emp Where comm. Is not null; Example 2:To display employee information for whose who are working as managers and receiving salary other than the range 2000 to 3000. SQL>select * from emp Where job=’manager’ and sal not between 2000 and 3000; Example 3:To display the employee details who are working in dept other than 20,30. 16 SQL>select * from emp Where deptno not in (20,30); Example 4:To display the employee details who are working in deptno 10,20 for their names not ending with ‘s’. SQL>select * from emp Where deptno in(10,20) and ename not like ‘%s’; In built functions: Are classified into five types o o o o Number Functions Character Functions Date functions Group functions Group Functions: 1. Sum(expr) 4.count(*) 2. avg(expr) 5. Max(expr) 3. count(expr) 6. min(expr) 1. Sum(expr): Is used to find total sum of the attribute or field mentioned. Example 1: Find the sum of total salary being paid to all the employees of the organizations. SQL>select sum(sal) from emp; 17 Example 2: Find the sum of salary and commission paid to the employees of deptno 10. SQL>select sum(sal+comm.) from emp Where deptno=10; 2. avg(expr): Is used to find the average of the attribute being mentioned. Example: Find the average amount salary being paid to each employee. SQL>select avg(sal) from emp; 3.Count(*): Is used to count the no.of records in the table,where the empty record is also counted. Example 1: find the no.of employees working in the organization. SQL>select count(*) from emp; Example 2:find the no.of employees working as managers and clerks in the organization. SQL>select count(*) from emp Where job in(‘manager’,’clerk’); 4.count(expr): Is used to count the no.of records will the expr is satisfied.If a record has a null value it will not count that record. Example 1: Find the no.of employees who are receiving the commission. SQL>select count(comm.) from emp; Example 2: Find the no.of employees who are receiving the commission corresponding to deptno.10,20. SQL>select count(comm) from emp Where deptno=10 or deptno=20; 5.max(expr): Is used to find the maximum value for the mentioned numerical attribute. Example 1: Find the employees who is paid the highest salary. SQL>select max(sal) from emp; 6.min(expr): Is used to find the minimum value for the mentioned numerical attribute. Example: find the employees who is paid the least salary. SQL>select min(sal) from emp; 18 Numerical Functions: abs(n) sqrt(n) power(n) mod(n) 1.abs(n): Is used to find the absolute value of n.dual is dummy table for Temporary manipulation. SQL>select abs(-5) from dual; 2.sqrt(n): Is used to find the square root of n. SQL>select sqrt(36) from dual; 3.power(n): Is used to find the value of m to the power of n. SQL>select power(3,2) from dual; 4.mod(m,n): Is used to find the remainder after dividing m by n. SQL>select mod(5,2) from dual; 19 CHARACTER FUNCTIONS: Length(str) Concate(str1,str2) Substr(str,pos,n) Ascii(char) Chr(n) 1. length(str): Returns the length of the string mentioned. SQL>select length(‘student’) from dual; 2. concat(str1,str2): Joints string1 and string2 ot form a new string. SQL>select concat(‘aaaa’,’bbbb’) from dual; 3. substr(str,pos,n): Returns the substring from the string from position pos cut n characters. 20 SQL>select substr(‘student’,3,4) from dual; 4. ascii(char): Returns the ascii value of the mentioned character. SQL>select ascii(‘a’) from dual; 5.chr(n): Returns the character for the ascii value n mentioned. SQL>select chr(68) from dual; 6.lower(str): Converts the given string into lower case. SQL>select lower(‘AAAA’) from dual; 21 8. upper(str): Converts the given string into upper case. SQL>select upper(‘dddd’) from dual; DATE FUNCTIONS: 1. add months(date,n): To add or remove given n months to the given data.Sysdate gives the system date. SQL>select sysdate from dual; SQL>select add_month(sysdate,3) from dual; 2. months between(date1,date2): Returns the no.of months between the two dates mentioned.Date1 is maximum value and date2 is minimum value.The output of this function is either float or integer value. SQL>select months_between(’29-oct-03’,’29-apr-03’) from dual; 3. Last day(date): Returns the last day in the month specified by the date mentioned. SQL>select last_day(sysdate) from dual; 22 Group by clause: Is used to group a set of repeated values corresponding to a particular column for which we want to apply group function. Example 1: To display the deptno. And total salary in each dept. SQL>select deptno,sum(sal) from emp Group by deptno; Example 2: To display the dept’s highest,lowest salary and no.of employees in each dept. SQL>select deptno,max(sal),min(sal),count(*) from emp group by deptno; Example 3: To display the no.of employees receiving commission corresponding to deptno 10,20 with their deptno. SQL>select deptno,count(comm.) from Emp where deptno=10 or deptno=20 Group by deptno; 23 Having Clause: Is used when we want to frame the condition of salary is greater than cannot be used with where clause. Example 1: To display the deptno.s for which total amount of salary is greater than 10,000. SQL>select deptno,sum(sal) from emp Group by deptno Having sum(sal)>10000; Example 2: To display the deptno.s along with their total salary for which total salary is greater than 10,000 corresponding to deptno 10,20. SQL>select deptno,sum(sal) from emp Where deptno in (10,20) Group by deptno Having sum(sal)>10000; Example 3 : To display the job’s along with the no.of employees working ,provided the highest salary corresponding to the job is greater than 3000 as well as the no.of employees working is more than 3. SQL>select job,count(*) from emp Where deptno in (10,20,30) Group by job Having max(sal)>2000 and count(*)>2; 24 Order by clause: Is used when we want to display the data in a sorted order. 1. Ascending order |asc| (default ordering) 2. Descending |desc| Example 1: To display the employee information in the ascending order of the empno. SQL> select * from emp Oreder by empno; Example 2: To display the employee information in the descending order of the salary. SQL>select * from emp Order by sal desc; Example 3: To display the employee information in the ascending order of the deptno,descending order of salary. SQL>select * from emp Order by deptno,sal desc; Example 4: To display the depts along with their total payment corresponding to deptno 10,20,30 for which n0.of employees are working is more than 2 and display based on the descending order of total salary. SQL>select deptno,sum(sal) from emp Where deptno in (10,20,30) Group by deptno Having count(*)>2 Order by sum(sal) desc; 25 SET OPERATORS: Union Intersection Minus 1. union: Is used to take distinct rows from more than one select statement.By using union all the duplication is not removed. Example 1: To display in deptno the job’s. 10 or 20. SQL>select job from emp Where deptno=10 Union Select job from emp Where deptno=20; Example 2: To display the job’s from emp. SQL>select job from emp Where deptno=10 Union all Select job from emp Where deptno=20; 2.intersect: Is used to take common rows from more than one select statement. 26 Example 1: To dispalyb the job’s in deptno. 10 and 20. SQL>select job from emp Where deptno=10 Intersect Select job from emp Where deptno=20; Example 2:To disaply the job’s in deptno. 10 and (20 or 30). SQL>select job from emp Where deptno=10 Intersect (select job from emp Where deptno=20 Union Select job from emp Where deptno=30); 2. minus: Is used to select the rows from more than first select statement which are not in the second statement. Example 1: To display the job’s in deptno.10 and not in 20. SQL>select job from emp Where deptno=10 Minus Select job from emp Where deptno=20; Example 2: To list the jobs which are unique to dept 10 as compare to 20 and 30. SQL>(select job from emp Where deptno=20 Union Select job from emp Where deptno=30) Minus (select job from emp Where deptno=10); 27 SUB QUERIES: when we are using more than one select statement to perform particular operation then we will be calling it as a subquery.In subquery the inner statement will be executed first and only noce as compared to the outer statement. Syntax: select ----------From<table name> Where(select ------); Example 1: To display all the employee’s information whose salary is greater than Smith’s salary. SQL>select * from emp Where sal>(select sal from emp Where ename=’SMITH’); Example 2: To display all the employee’s information who is receiving the highest salary. 28 SQL>select * from employee Where sal=(select max(sal) from emp); Example 3: To display all the employee’s information whose job is same like Smith at the same time salary greater than Allen. SQL>select * from emp Where job=(select job from emp where ename=’SMITH’) And sal>(select sal from emp Where ename=’ALLEN’); Example 4:To display all the employee’s information who is receiving salary greater than average salary of all the employee’s. SQL>select * from emp Where sal>(select avg(sal) from emp); Example 5:To display the manager no.alng with the no.of employee’s working under him should be maximum no.of employees compared with the other members. SQL>select mgr,count(*) from emp Group by mgr Having count(*)=(select max(count(*) from Emp group by mgr); Example 6: To display the employee information under which maximum no.of employee’s working. SQL>select * from emp Where empno=(select mgr from emp Group by mgr) Having count(*)=(select max(count(*) fom emp group by mgr); Example 7: To disaply all the employee’s information who is receiving the second highest salary. SQL>select * from emp Where sal=(select max(sal) from emp where Sa<(select max(sal) from emp)); 29 When the subquery is returning more than one value to frame the condition we have to use all or any. Example 8: To display the employee information whose salary is greater than all the employees salaries of deptno 20. SQL>select * from emp Where sal>all(select sal from emp Where deptno=20); Views: Views can be defined as a virtual table because it doesn’t exist by itself,unless you are having one or more ordinary table on which it will be based or dependent.The table on which view is based is called as base table of the view.It is possible to insert,update and delete the data in the view in the same way as in the table. Advantages of views: 30 Providing the security for the table. By giving limited access to your table to other users. Complicated queries can be generated by using views a normal simple table creation. Creation of view: Syntax: create view <view name> As select ------ from <table name>; Example 1: To create a view for emp table with empno,name,salary. SQL>craerte view empview As select empno,ename,sal from emp; Example 2: To create a view for emp table for dept 10. SQL>create view d10view As select * from emp Where deptno=10; Insert into view: Example 1: Insert a new record into view empview. SQL>insert into empview Values(101,’WILLIAM’,2000); Viewing the contents of d10view: Example: To display the contents of d10view. SQL>select * from d10view; 31 Replace: Replace option is used whenever you want to over write the existing select statement with new select statement. Example: To create empview with empno,name,salary and deptno. SQL>replace view empview As select empno,ename,sal,deptno from emp; With check option: When ever you want to restrict the user to insert thr records which are satisfying the where condition of the view then we use with check option. Syntax: create view <view name> As select-----from <table name> Where <condition> With check option; Example : create a view for employee details of deptno. 20 SQL>create view d20view As select * from emp 32 Where deptno=20 With check option; If you try to enter deptno other than 20,it will not be accepted into the view. Sequences: Whenever you want to create a object which is going to generate the numbers in a particular order (i.e. interval) then we will be calling a sequence. Syntax: create sequence <seq.Name> Start with <no.> Increment by <interval> Maxvalue <n> Minvalue <n> Cache Cycle; Whenever you want to generate the next number of the sequence then we will be using nextval and when you want to see the current position of the sequence we use currval. Example: SQL>create sequence eno Start with 5 Increment by 1 Minvalue 5 Maxvalue 15 Cache 5 Cycle; This is going to create a sequence with name eno starting with 5,incrementing by 1,minimum value is 5,maximum value is 15,cache is 5 and with cycle. Altering the sequence: whenever you want to change any options related t To existing sequence then we will be using Alter. Note:start with cannot be changed using Alter. Syntax: Example: alter sequence <seq.name> <options to be changed>; SQL>alter sequence eno Increment by 2 Minvalue 10 Maxvalue 100; 33 Drop sequence: Whenever you want to drop a sequence we use drop statement. Syntax: drop sequence <seq.name> Example: SQL>drop sequence eno; INDEX: Whenever you to retrieve the records faster corresponding to one condition then we will be using Indexing concept. Before going to index,identify the fields which will be using mostly in the where clause then indx on those fields.Apply index when there are more than 500 records are present in a table. There are 3 types of indexes Simple index, Unique index and Concatenated index. Syntax: SQL>create index <index name> on <table name>(<field name>); 1. Simple index: Is used when indexing is based on the column of the table. Example 1: SQL>create index idept on emp(deptno); Example 2: SQL>create index iename on emp(ename): 2. Unique index: Is used when indexing is based on implementing unique constraint along with indexing. Example : SQL>create unique index iph on emp(phno); 3. concatenated index: Is used when indexing is based on more than one column as a combination. Example: SQL>create index ds on emp(deptno,sal); Delete index: drop statement is used Example: SQL>drop index idept; 34 PL/SQL(Procedural Language using sql) PL/SQL can be called the extension of SQL where it is going to support the SQL statement along with the processing statement we will be calling it as Procedural Language. PL/SQL is divided into 3 parts 1.Declaration part: Declaring the variables. 2.Execution part: corresponding to the task all the statements are be written here. 3.Exception part: Errors are to be handled properly. to DBMS output.put line(string): Is a function used to print message on the screen.before using this function set serveroutput on. SQL>set serveroutput on; %type: Is used in declaring whenever we want to assign the same datatype and size of one variable to another variable. Example: sall emp.sal%type;/*sall is of same type&size as that of sal field in emp table*/ Syntax: Declare : /*Declaring block*/ Begin : /*Execution block*/ Exception : /*Exception block*/ End; Example: Write a PL/SQL block which finds area of a circle. SQL>ed area Declare R number(2):=10; Pi constant number(4,3):=3.14; A number(7,2); Begin A:=Pi*R*R; DBMS_output.put_line(‘area is=’||to_char(a)); End; / 35 SQL>@area; /* To execute the PL/SQL block*/ Example: Write a PL/SQL block which accepts the empno and if an employee doesn’t have commission,he will get 10% of his salary as commission. Select <var> into <PL/SQL var>; SQL>ed mcom Declare Eno number(5):=&emp Comm1 emp1.comm%type; Sal1 emp1.sal%type; Begin Select comm.,sal into comm1,sal1 from emp Where empno=eno; If comm1 is null then Update emp1 Set comm.=sal*.1 Where empno=eno; Else DBMS_output.put_line(‘Commission is existing for’||to_char(eno)); End if; End; / SQL>@mcom; TRIGGER: Triggers are procedures that are sotored in the database not in the complied form and implicitly fired when an event occurs.Traditionally,triggers guarantee that when a specific operation is performed related actions are performd.Triggers support the execution of a Pl/SQL block when an INSERT<UPDATE,or DELETE occurances on a table view. Advantages of Triggers: Applying Complex Bussiness rules. Security. Auditing. Syntax: Create or replace trigger <trigger name> 36 Before/after insert or delete or update on <table name> for each row. Begin : : End; Example 1: Create a database Trigger corresponding to emp table which is not going to allow the user to insert the employee’s salary more than 5000. SQL>ed t1 Create or replace trigger eins Before insert on emp for each row Begin If:new.sal>5000 then Raise_application_erroe(-20001,’salary above 5000’); End if; End; / SQL>@t1 Example 2: Create a database Trigger on dept table which prevents the user from updating the deptno or deleting a row from the dept table if dependent rows are existing in the emp table( i.e. if there are any employee’s belonging to that department). 37 SQL>ed t2 Create or replace trigger updel Before update or delete on dept for each row Begin Declare No number(4); If updating or deleting then Select count(*) no from emp Where deptno=:new.deptno; If (no>1) then Raise_application_erroe(-20001,’Records existing in emp table’); End if; End if; End; / SQL>@ t2 38 /*PL/SQL program for checking if a number is prime or not*/ SQL>ed prime.sql Declare N number:=&n; I number:=2; R number(3):=0; Begin While(i<=n/2) Loop R:=mod(n,i); If r=0 then Exit; End if; I:=i 1; End loop; If r=1 then Dbms_output.put_line(‘prime’); else dbms_output.put_line(‘not prime’); end if; end; / SQL>@ prime; OUTPUT: 39 /*PL/SQL Program for calculating telephone bill*/ SQL>create table telbill (tno number(10), Name char(15), Address varchar2(15), Prev number(5), Present number(5), Pay number(9,2)); SQL>insert into telbill(tno,name,address,prev,present) values(&tno,’&name’,’&address’,&prev,&present); Declare Cursor t1 is select tno,prev,present from telbill order by present desc; Tree t1%row type; Diff telbill.prev%type:=0; Begin Open t1; Loop Fetch t1 into trec; Exit when t1%notfound; Diff:=trec.present-trec.prev; If diff between 0 and 200 then Update telbill Set pay=diff*0.80 Where tno=trec.tno; 40 Elsif diff between 200 and 400 then Update telbill Set pay=160+(diff-200)*1 Where tno=trec.tno; Else Update telbill Set pay=160+200+(diff-400)*1.25 Where tno=trec.tno; End if; End loop; Close t1; End; / 41 /*PL/SQL Program for Displaying the salesperson who has reached the Target*/ . SQL>create table sales1 (sno number(2), Sname char(15), Sbr cahr(15), Tgt number(5)); SQL>insert into sales1 Values(&sno,’&sname’,’&sbr’,&tgt); Declare Cursor s1 is select * from sales1 order by sbr desc; Srec s1%rowtype; Begin Open s1; Dbms_output.put_line(‘SALES PERSON WHO HAVE REACHED THE TARGET’); Dbms_output.put_line(‘-----------------------------------------------‘); Loop Fetch s1 into srec; Exit when s1%notfound; If srec.tgt>=7500 then Dbms_output.put_line(‘--------------------------------------------‘); Dbms_output.put_line(‘sales person name=’||srec.sname); Dbms_output.put_line(‘branch name=’||srec.sbr); End if; End loop; 42 Close s1; End; / 43 /*PL/SQL program for calculating electricity bill*/ SQL>create table elect (eno number(5), Ename char(15), Address varchar2(15), Prev number(5), Pres number(5),pay number(9,2)); SQL>insert into elect(eno,ename,address,prev,pres) Values(&eno,’&ename’,’&address’,&prev,&pres); Declare Cursor e1 is select cno,prev,pres from elect order by eno desc; Erec e1%rowtype; Diff elect.prev%type:=0; Begin For erec in e1 Loop Diff:=erec.pres-erec.prev; If diff between 0 an 500 then Update elect Set pay=diff*0.80 Where cno=erec.cno; 44 Elsif diff between 0 and 1000 then Update elect Set pay=diff*1.20 Where cno=erec.cno; Elsif diff between 0 and 1500 then Update elect Set pay=diff*1.60 Where cno=erec.cno; Elsif diff between 0 and 2000 then Update elect Set pay=diff*2 Where cno=erec.cno; Else Update elect Set pay=diff*2.50 Where cno=erec.cno; End if; End loop; End; / 45 /*Program for displaying Multiplication table of a given number*/ Declare Num number (2):=&no1; Res number(2); Begin For I in 1…10 Loop Res:=num*I; Dbms_output.put_line(num||’*’||’=’||res); End loop End; / 46 /*Program to check if a given no.is Perfect Square or not*/. Declare Num number(2):=&no; N number(2); Flag number(1):=0; Begin N:=num/2; For I in 1…n Loop Ifmod(num,i)=0 and i*i=num then Flag:=1; Dbms_output.put_line(num||’is a perefect square’); Exit; End if; End loop; If flag=0 then Dbms_output.put_line(num||’is not a perfect square’); End if; End; / 47 /*Program to check if a given string is Palindrome or not*/ Declare S varchar2(10):=’&str’; Len number(2); C char(1); T varchar2(10); Begin Select length(s) into len from dual; For i in reverse 1..len Loop C:=substr(s,I,1); T:=concat(t,c); End loop; If s=t then Dbms_output.put_line(s||’is a palindrome’); Else Dbms_output.put_line(s||’is not a palindrome’); End if; End; / 48 /*Program to generate Fibonacci Series*/ SQL>create table fibo (fs number(5)); Declare F1 number(3):=0; F2 number(3):=1; F3 number(3):=0; J number(3):=&limit; Begin For I in 1..j Loop F3:=f1+f2; Dbms_output.put_line(to_char(f3)); Insert into fibo Value(f3); F1:=f2; F2:=f3; End loop; End; / 49 /*Program for generating the Pay Slip for each Employee No.given*/ Declare I number(5):=&eno; Cursor e is select empno,ename,sal from emp where empno=I; No emp.empno%type; Name emp.ename%type; S emp.sal%type; Da number(7,2); Hra number(7,2); Pf number(7,2); Net number(7,2); Begin Open e; Loop Fetch e into no,name,s; Exit when e%notfound; Dbms_output.put_line(‘______________________’); Dbms_output.put_line(‘******STAR COMPANY******’); Dbms_output.put_line(‘*****PAY SLIP********’); Dbms_output.put_line(‘____________________’); Dbms_output.put_line(‘empno=’||no); Dbms_output.put_line(‘emplyee name’||name); Dbms_output.put_line(‘basic salary=’||s); Da:=s&0.025; Dbms_output.put_line(‘da=’||da); Hra:=s*0.05; Dbms_output.put_line(‘hra=’||hra); Pf:=s*0.015; Dbms_output.put_line(‘pf=’||pf); Net:=s+da+hra-pf; Dbms_output.put_line(‘gross salary=’||net); End loop; Close e; End; / 50 /*Program to insert in the table & display the Division of the given Student*/ SQL>create table s (rno number(3), M number(3), S number(3), C number(3), Div varchar(20)); Declare R number(3):=&rollno; M1 s.m%type; S1 s.s%type; C1 s.c%type; D s.div%type; P number(7,2):=0; Begin Select m,s,c into m1,s1,c1 from s where rno=r; P:=(m1+s1+c1)/3; If p>70 then D:=’distinction’; Elsif p between 60 and 70 then D:=’first division’; Elsif p>=50 and p<=60 then D:=’second division’; Elsif p>=40 and p<=50 then D:=’third division’; Else D:=’fail’; End if; Update s Set div=d Where rno=r; Dbms_output.put_line(‘result=’||d); End; / 51