SQL BASICS The structure queries language is a language that enable to create and operate on relational database ,which are sets of related information stored in tables .SQL has clearly established itself as the standard relational database language. PROCESSING CAPABILITY OF SQL: The various capability of sql are: 1. DATA DEFINITION LANGUAGE(DDL): The sql DDL provides commands for defining relations schemas ,deleting relations ,creating index and modifying relations schemas. 2. INTERACTIVE DATA MANIPULATION LANGUAGE(DML): The sql DML includes the queries language based on both the relational algebra and the tuples relational calculas. It includes also command to insert ,delete and modifying in the database. 3. EMBEDDED DATA MANIPULATION LANGUAGE: The embedded form of sql is designed for use within general purpose programming language such as pl/1,cobol ,fortran,pascal and c. 4. VIEW DEFINITION : The sql DDL also includes commands for defining views 5. AUTHORIZATION : The sql DDL includes command for specifying access rights to relation and views. 6. INTEGRITY: The sql provides forms of integrity checking. Future products and standard of sql are likely to include enhanced features for integrity checking . 7. TRANSACTION CONTROL: Sql includes command for specifying the beginning and ending of transaction along with commands to have a control over transaction processing. EX: NO: 1 DATA DEFINITION LANGUAGE (DDL) COMMANDS Aim: To execute and verify the Data Definition Language commands and constraints 1.1 DDL (DATA DEFINITION LANGUAGE) ● ● ● ● ● ● CREATE ALTER DROP RENAME TRUNCATE COMMENT Procedure: STEP 1: Start STEP 2: Create the table with its essential attributes. STEP 3: Execute different Commands and extract information from the table. STEP 4: Stop SQL COMMANDS 1. Command name : CREATE Command description: CREATE command is used to create objects in the database. 2. Command name : ALTER Command description: ALTER command is used to alter the structure of database 3. Command name : DROP Command description: DROP command is used to delete the object from the database. 4. Command name : RENAME Command description: RENAME command is used to rename the objects. 5. Command name : TRUNCATE Command description : TRUNCATE command is used to remove all the records from the table 6. Command Name : COMMENT Command description : COMMENT allows to store some comments about tables, views or columns in the data dictionary 1) Creating a table Syntax for creating a table: SQL: create <obj.type> <obj.name> (column name.1 <datatype> (size), column name.1 <datatype> (size) ……………………………); Q1. Write a query to create a table employee with empno, ename, designation, and salary. SQL>create table emp (empno number (4), ename varchar2 (10), designation varchar2 (10), salary number (8,2)); Table created. Describing the table: Syntax for describe the table: SQL: desc <table name>; Q2. Write a query to display the column name and data type of the table employee. SQL> desc emp; Name null? Type ----------------------------------------- -------- ------------Empno number(4) Ename varchar2(10) Designation varchar2(10) Salary number(8,2) Creating a table from an Existing Table With All Fields Syntax SQL> create table <traget table name> select * from <source table name>; Q3. Write a query for create a from an existing table with all the fields SQL> create table emp1 as select * from emp; Table created. SQL> desc emp1 Name null? Type ----------------------------------------- -------- -----------------Empno number(4) Ename Designation Salary varchar2(10) varchar2(10) number(8,2) Creating a table from an Existing Table With Selected Fields Syntax SQL> create table <traget table name> select empno, ename from <source table name>; Q4. Write a query for create a from an existing table with selected fields SQL> create table emp2 as select empno, ename from emp; Table created. SQL> desc emp2 Name null? Type ----------------------------------------- -------- ---------------------Empno number (4) Creating a new table from an existing table without any record Syntax SQL> create table <traget table name> as select * from <source table name> where <false condition>; Q5. Write a query for create a new table from an existing table without any record: SQL> create table emp3 as select * from emp where 1>2; Table created. SQL> desc emp3; Name null? Type ----------------------------------------- -------- -----------------------Empno number(4) Ename varchar2(10) Designatin varchar2(10) Salary number(8,2); 2) Alter & modification on table Alter & Modify on a Single Column: Syntax : SQL > alter <table name> modify <column name> <datatype> (size); Q6. Write a query to alter the column empno number (4) to empno number (6). SQL>alter table emp modify empno number (6); Table altered. SQL> desc emp; Name null? Type ----------------------------------------- -------- ---------------------------Empno number(6) Ename varchar2(10) Designatin varchar2(10) salary number(8,2) Altering a table with multiple column: Syntax : SQL > alter <table name> modify <column name1> <datatype> (size), modify <column name2> <datatype> (size) ………………………………………….; Q7. Write a Query to Alter the table employee with multiple columns (empno, ename.) SQL>alter table emp modify (empno number (7), ename varchar2(12)); Table altered. SQL> desc emp; Name null? Type ----------------------------------------- -------- ---------------------------Empno Ename Designation Salary number(7) varchar2(12) varchar2(10) number(8,2); Adding a new column Syntax: SQL> alter table <table name> add (<column name> <data type> <size>); Q8. Write a query to add a new column in to employee SQL> alter table emp add qualification varchar2(6); Table altered. SQL> desc emp; Name null? Type ----------------------------------------- -------- ---------------------------Empno number(7) Ename varchar2(12) Designation varchar2(10) Salary number(8,2) Qualification varchar2(6) Adding a multiple columns Syntax: SQL> alter table <table name> add (<column name1> <data type> <size>,(<column name2> <data type> <size>, ………………………………………………………………); Q9. Write a query to add multiple columns in to employee SQL>alter table emp add (dob date, doj date); Table altered. SQL> DESC EMP; Name null? Type ----------------------------------------- -------- ---------------------------Empno number(7) Ename varchar2(12) Designation varchar2(10) Salary number(8,2) Qualification varchar2(6) Dob date Doj date 3) REMOVE / DROP Dropping a new column Syntax: SQL> alter table <table name> drop column <column name>; Q10. Write a query to drop a column doj from an existing table employee SQL> alter table emp drop column doj; Table altered. SQL> desc emp; Name null? Type ----------------------------------------- -------- ------------Empno number(7) ename varchar2(12) designation varchar2(10) salary number(8,2) qualification varchar2(6) dob date Dropping multiple columns Syntax: SQL> alter table <table name2>,……………………………..; name> drop Q11. Write a query to drop multiple columns from employee SQL> alter table emp drop (dob, qualification); Table altered. SQL> desc emp; Name null? Type ----------------------------------------- -------- -------------Empno number(7) Ename varchar2(12) Designation varchar2(10) Salary number(8,2) 4) RENAME Syntax: SQL> alter table rename <old name> to <new name> Q12. Write a query to rename table emp to employee SQL> alter table emp rename emp to employee; SQL> desc employee; Name null? Type ----------------------------------------- -------- -------------Empno number(7) Ename varchar2(12) Designation varchar2(10) Salary number(8,2) <column name1>,<column 5) TRUNCATE Syntax: Truncate table table_name; Q13. Write a query to truncate the table employee SQL> truncate table employee; Table truncated Difference between DROP and TRUNCATE Statement: If a table is dropped, all the relationships with other tables will no longer be valid, the integrity constraints will be dropped, grant or access privileges on the table will also be dropped, if want use the table again it has to be recreated with the integrity constraints, access privileges and the relationships with other tables should be established again. But, if a table is truncated, the table structure remains the same, therefore any of the above problems will not exist. 6) COMMENT The comment statement allows to store some comments about tables, views or columns in the data dictionary Syntax: SQL> --Add a comment on a table, issue the following command: SQL > comment on table <table name> is “comments” Q14. Write a query to write the comments “this is a table for employee” on the emp table. SQL> comment on table emp is 'This is a table for Employee.'; Comment created. The comments for tables and views can be retrieved with something like Syntax: select table_name, comments from user_tab_comments where table_name like 'SOME%'; Table_name comments ------------------------------ -------------------------------------------------SOME_TABLE some hopefully meaningful comment for some_table SOME_VIEW Views can also be commented, yet the statement is still: comment on table SQL> select table_name, comments from user_tab_comments Table_Name Comments Emp 'This is a table for Employee” Dept Setting of CONSTRAINTS Constraints are part of the table definition that limits and restriction on the value entered into its columns. TYPES OF CONSTRAINTS: ● ● ● ● ● ● Primary key Foreign key/references Check Unique Not null Null Default CONSTRAINTS CAN BE CREATED IN THREE WAYS: ● Column level constraints ● Table level constraints ● Using DDL statements-alter table command Column level constraints are applicable to that column only, whereas table level constraints are used to define composite keys like primary key for the combination of two or more columns in a table OPERATION ON CONSTRAINT: i) ENABLE ii) DISABLE iii) DROP 1) Primary key Column level constraints Using Primary key Syntax: SQL:> create table tablename(column name.1 <datatype> (size)<type of constraints> , column name.1 <datatype> (size) ……………………………); Q1. Write a query to set a primary key on empno of employee table. SQL> create table employee(empno number(4) primary key, ename varchar2(10), job varchar2(6), sal number(5), deptno number(7)); SQL> desc employee1; Name Null? Type ----------------------------------------- -------- ---------------------------Empno not null number(4) ename varchar2(10) job varchar2(6) sal number(5) deptno number(7) Column level constraints Using Primary key with naming convention Syntax: SQL: > create table tablename (column name.1 <datatype> (size) constraints <name of the constraints> <type of the constraints> , column name.1 <datatype> (size) ……………………………); Q2. Write a query to set a primary key constraint EMP_EMPNO_PK on empno of employee table. SQL> create table employee(empno number(4) constraint emp_empno_pk primary key, ename varchar2(10), job varchar2(6), sal number(5), deptno number (7)); SQL> desc employee; Name Null? Type ----------------------------------------- -------- ---------------------------- Empno ename job sal deptno not null number(6) varchar2(20) varchar2(6) number(7) number(5) Table Level Primary Key Constraints Syntax for Table level constraints Using Primary key: SQL: >create table <tablename> (column name.1 <datatype> (size) , column name.1 <datatype> (size), constraints <name of the constraints> <type of the constraints>); Q3. Write a query to set a primary key constraint EMP_EMPNO_PK on empno of employee table. SQL> create table employee (empno number(6), ename varchar2(20), job varchar2(6), sal number(7), deptno number(5), constraint emp_empno_pk primary key(empno)); Table level constraint with alter command (primary key): Syntax for Column level constraints Using Primary key: SQL:> create table <tablename> (column name.1 <datatype> (size), column name.1 <datatype> (size) ); SQL> alter table <table name> add constraints <name of the constraints> <type of the constraints> <column name>); Q4. Write a query to create employee table with the following column empno, ename, job, sal , deptno and alter the table to add the primary key constraint SQL> create table employee(empno number(5), ename varchar2(6), number(6), deptno number(6)); job varchar2(6), Sal SQL> desc employee; Name null? Type ----------------------------------------- -------- ---------------------------empno number(5) ename varchar2(6) job varchar2(6) sal number(6) deptno number(6) SQL>alter table emp3 add constraint emp3_empno_pk primary key (empno); SQL> desc employee; Name null? Type ----------------------------------------- -------- ---------------------------empno not null number(5) ename varchar2(6) job varchar2(6) sal number(6) deptno number(6) Reference /foreign key constraint Column level foreign key constraint Parent Table: Syntax for Column level constraints Using Primary key: SQL:> create table <tablename> (column name.1 <datatype> (size)<type of constraints> , column name.1 <datatype> (size) ……………………………); Child Table: Syntax for Column level constraints Using foreign key: Sql:> create table <tablename> (column name.1 <datatype> (size), column name2 <datatype> (size) references <table name> (column name> ………………); Q5. Write a query to set a foreign key on deptno of employee table that refers the dept table. SQL> create table dept(deptno number(2) primary key, varchar2(15)); dname varchar2(20), location SQL>create table emp4 (empno number(3), deptno number(2) references dept(deptno), design varchar2(10)); Column level foreign key constraint with naming conversions: Parent Table: Syntax for Column level constraints Using Primary key: SQL:> create table <tablename> (column name.1 <datatype> (size)<type of constraints> , column name.1 <datatype> (size) ……………………………); Child Table: Syntax for Column level constraints using foreign key: Sql:> create table <tablename> (column name.1 <datatype> (size) , column name2 <datatype> (size) constraint <const. Name> references <table name> (column name> ……………………………); Q.6. Write a query to create foreign key constraints with column level SQL> create table dept1 (deptno number(2) primary key, varchar2(15)); dname varchar2(20), Location SQL> create table emp4a (empno number(3), deptno number(2)constraint emp4a_deptno_fk references dept(deptno), design varchar2(10)); SQL> desc dept1; Name null? Type ----------------------------------------- -------- ---------------------------deptno not null number(2) dname varchar2(20) location varchar2(15) SQL> desc emp4; Name null? Type ----------------------------------------- -------- ---------------------------empno number(3) deptno number(2) design varchar2(10) Table Level Foreign Key Constraints Parent Table: SQL:> create table <tablename> (column name.1 <datatype> (size)<type of constraints> , column name.1 <datatype> (size) ……………………………); Child Table: Syntax for Table level constraints using foreign key: SQL:> create table <tablename> (column name.1 <datatype> (size), column name2 <datatype> (size), constraint <const. Name> references <table name> (column name> ); Q.7. Write a query to create foreign key constraints with Table level SQL> create table dept3 (deptno number (2) primary key, dname varchar2(20), Location varchar2(15)); SQL> create table emp5 (empno number(3), deptno number(2), design varchar2(10) constraint enp4_deptno_fk foreign key (dept no) references dept3 (deptno)); Table Level Foreign Key Constraints with Alter command Parent Table: SQL:> create table <tablename> (column name.1 <datatype> (size)<type of constraints> , column name.1 <datatype> (size) ……………………………); Child Table: Syntax for Table level constraints using foreign key: SQL:> create create table <tablename> (column name.1 <datatype> (size) , column name2 <datatype> (size)); SQL> alter table <table name> add constraint <const. Name> References <table name> (column name>); Q.8. Write a query to create foreign key constraints with Table level with alter command. SQL> create table dept1 (deptno number(2) primary key, dname varchar2(20), Location varchar2(15)); SQL> create table emp5 (empno number(3), deptno number(2), design varchar2(10)); SQL>alter table emp5 add constraint emp5_deptno_fk foreign key (deptno) references dept1(deptno); SQL> desc dept1; Name null? Type ----------------------------------------- -------- ---------------------------deptno not null number(2) dname varchar2(20) location varchar2(15) SQL> desc emp5; Name null? Type ----------------------------------------- -------- ---------------------------empno number(3) deptno number(2) design varchar2(10) SQL> alter table emp5 add constraint emp5_deptno_fk foreign key (deptno) references dept1(deptno); Table altered. SQL> desc emp5; Name null? Type ----------------------------------------- -------- ---------------------------empno number(3) deptno number(2) design varchar2(10) SQL> drop table dept1; drop table dept1 * ERROR at line 1: ORA-02449: unique/primary keys in table referenced by foreign keys Check constraint Column Level Check Constraint Syntax for clumn level constraints using Check: SQL:> create create table <tablename> (column name.1 <datatype> (size) constraint <constraints name> <type of constraints> (constraitns criteria) , column name2 <datatype> (size)); Q.9. Write a query to create Check constraints with column level SQL> create table emp7(empno number(3), ename varchar2(20), design varchar2(15), sal number(5)constraint emp7_sal_ck check(sal>500 and Sal<10001), deptno number(2)); Table Level Check Constraint Syntax for Table level constraints using Check: SQL:> create table <tablename> (column name.1 <datatype> (size), (column name2 <datatype> (size), constraint <constraints name> <type of constraints > (constraitns criteria)) ; Q.10. Write a query to create Check constraints with table level SQL> create table emp8(empno number(3), ename varchar2(20), design varchar2(15), sal number(5),deptno number(2), constraints emp8_sal_ck check(sal>500 and sal<10001)); Check Constraint with Alter Command Syntax for Table level constraints using Check: SQL:> create table <tablename> (column name.1 <datatype> (size), (column name2 <datatype> (size), constraint <constraints name> <type of constraints> (constraitns criteria)) ; Q.11. Write a query to create Check constraints with table level using alter command SQL> create table emp9(empno number, ename varchar2(20), design varchar2(15), Sal number(5)); SQL> alter table emp9 add constraints emp9_sal_ck check (sal>500 and sal<10001); Unique Constraint Column Level Constraint Syntax for Column level constraints with Unique: SQL :> create table <tablename> (<column name.1> <datatype> (size) constraint <name of constraints> <constraint type>, (column name2 <datatype> (size)) ; Q.12. Write a query to create unique constraints with column level SQL> create table emp10(empno number(3), ename varchar2(15)constraint emp10_design_uk unique, sal number(5)); Table Level Constraint varchar2(20), desgin Syntax for Table level constraints with Unique: SQL :> create table <tablename> (<column name.1> <datatype> (size), (column me2 <datatype> (size), constraint <name of onstraints> <constraint type>(column name);) ; Q.13. Write a query to create unique constraints with table level SQL>create table emp11(empno number(3), ename varchar2(20), design number(5),constraint emp11_design_uk unigue(design)); varchar2(15), sal Table Level Constraint Alter Command Syntax for Table level constraints with Check Using Alter SQL :> create table <tablename> (<column name.1> <datatype> (size), (column name2 <datatype> (size)) ; SQL> alter table add <constraints> <constraints name> <constraints type> (column name); Q.14. Write a query to create unique constraints with table level SQL> create table emp12 (empno number(3), ename varchar2(20), design varchar2(15), sal number(5)); SQL> alter table emp12 add constraint emp12_design_uk Unique(desing); Not Null Column Level Constraint Syntax for Column level constraints with Not Null SQL :> create table <tablename> (<column name.1> <datatype> (size) constraint <name of constraints> <constraint type>, (column name2 <datatype> (size)) ; Q.15. Write a query to create Not Null constraints with column level SQL> create table emp13 (empno number(4), ename varchar2(20) constraint emp13_ename_nn not null, design varchar2(20), sal number(3)); Null Column Level Constraint Syntax for Column level constraints with Null: SQL :> create table <tablename> (<column name.1> <datatype> (size) constraint <name of constraints> <constraint type>, (column name2 <datatype> (size)) ; Q.16. Write a query to create Null constraints with column level SQL> create table emp13 (empno number(4), ename varchar2(20) constraint emp13_ename_nn null, design varchar2(20), sal number(3)); Constraint Disable \ Enable Constraint Disable Syntax: SQL> alter table <table-name> disable constraint <constraintName> Q.17. Write a query to disable the constraints SQL>alter table emp13 disable constraint emp13_ename_nn null; Constraint Enable Syntax: SQL> alter table <table-name> enable constraint <constraintName> Q.18. Write a query to enable the constraints SQL>alter table emp13 enable constraint emp13_ename_nn Null; EX: NO: 2 Implementation of Data Manipulation Language (DML) Commands (Performing Insertion, Deletion, Modifying, Updating and Viewing and writing SQL queries to retrieve information from the database) Aim: To execute and verify the DML commands DML (DATA MANIPULATION LANGUAGE) ● ● ● ● SELECT INSERT DELETE UPDATE PROCEDURE STEP 1: Start STEP 2: Create the table with its essential attributes. STEP 3: Insert the record into table STEP 4: Update the existing records into the table STEP 5: Delete the records in to the table STEP 6: use save point if any changes occur in any portion of the record to undo its original state. STEP 7: use rollback for completely undo the records STEP 6: use commit for permanently save the records. SQL COMMANDS 1. Command name Command description 2. Command name Command description 3. Command name Command description 4. Command name Command description : insert : insert command is used to insert objects in the database. : select : select command is used to select the object from the database. : update : update command is used to update the records from the table : delete : delete command is used to delete the records form the table 1) INSERT Syntax for Insert Records in to a table: SQL :> insert into <table name> values< val1, 'val2',…..); Q1. Write a query to insert the records in to employee. SQL>insert into emp values(‘x’, ‘manager’,30000); 1 row created. SQL> select * from employee; Name designation salary -------------------- -------------------- ---------x manager 30000 y supervisor 20000 z salesrep 20000 INSERT A RECORD USING SUBSITUTION METHOD Syntax for Insert Records into the table: SQL :> insert into <table name> values< '&column name', '&column Name 2',…..); Q2. Write a query to insert the records in to employee using substitution method SQL > insert into employee values ('&name', '&designation', &salary) Enter value for name: a Enter value for designation: sales rep Enter value for salary: 20000 old 1: insert into employee values('&name','&designation',&salary) new 1: insert into employee values('a','sales rep',20000) 1 row created. SQL> / Enter value for name: b Enter value for designation: clerk Enter value for salary: 25000 old 1: insert into employee values('&name','&designation',&salary) new 1: insert into employee values('b','clerk',25000) 1 row created. SQL> / Enter value for name: c Enter value for designation: junior assistant Enter value for salary: 22000 old 1: insert into employee values('&name','&designation',&salary) new 1: insert into employee values('c','junior assistant',22000) 1 row created. SQL> select * from employee; Name designation salary -------------------- -------------------- ---------x manager 30000 y supervisor 20000 z salesrep 20000 a sales rep 20000 b clerk 25000 c junior assistant 22000 6 rows selected. 2) SELECT Syntax for displaying all Records from the table: SQL> select * from <table name>; Q3. Write a query to display the records from employee. SQL> select * from employee; Name designation salary -------------------- -------------------- ---------x manager 30000 y supervisor 20000 z salesrep 20000 a sales rep 20000 b clerk 25000 c junior assistant 22000 6 rows selected. Syntax for selecting single column from the table SQL> select <column name> from <table name>; Q4. Write a query to list all employee names from employee. SQL> select name from employee; Name -------------------x y z a b c 6 rows selected. Syntax for selecting multiple columns from the table SQL> select <column name1>, <column name2> from <table name>; Q5. Write a query to list all employee names along with their salary from employee. SQL> select name, salary from employee; NAME SALARY -------------------- ---------x 30000 y 20000 z 20000 a b c 20000 25000 22000 6 rows selected. Syntax for selection with arithmetic operation SQL> select <column name1><arithmetic operation>, <column name2> from <table name>; Q6. Write a query to list all employee names , their salaries and also add 1000 rupees to the salaries of all employees. SQL> select name, salary+1000 from employee; Name salary+1000 -------------------- ----------x 31000 y 21000 z 21000 a 21000 b 26000 c 23000 6 rows selected. Syntax for selection with alias SQL> select <column name1> “ alias” , <column name2> from <table name>; Q7. Write a query to list all employee names , their salaries and also add 1000 rupees to the salaries of all employees. Display the salary column with the name “with bonus” SQL> select name, salary+1000 "with bonus" from employee; or SQL> select name, salary+1000 as "with bonus" from employee; Name with bonus -------------------- ----------x 31000 y 21000 z 21000 a 21000 b 26000 c 23000 6 rows selected. Syntax for rename a column during selection: SQL> select <column name> “new name” from <table name>; Q8. Write a query to list all employee names along with their salary from employee but the display the column salary as sal in the result. SQL> select name, salary "sal" from employee; NAME sal -------------------- ---------x 30000 y 20000 z 20000 a 20000 b 25000 c 22000 6 rows selected. Syntax for selection with concatenation operator SQL> select <column name1> || || <column name2> from <table name>; Q9. Write a query to concatenate all employee names along with their salary from employee in the result. SQL> select name||salary from employee; Name||salary -----------------------------------------------------------x30000 y20000 z20000 a20000 b25000 c22000 6 rows selected. Syntax for selection with literal character strings SQL> select <column name1 || ‘ ‘ || ‘ character strings’ || ‘ ‘ ||<column name2> from employee; Q10. Write a query to list all employee names along with their salary from employee and include the character strings in the result SQL> select name||' '||'is getting'||' '||salary from employee NAME||''||'ISGETTING'||''||SALARY -----------------------------------------------------------------------x is getting 30000 y is getting 20000 z is getting 20000 a is getting 20000 b is getting 25000 c is getting 22000 Syntax for selecting distinct values SQL> select distinct <column name1 > from employee; Q11. Write a query to list unique employee names SQL> select * from employee; Name designation salary -------------------- -------------------- ---------x manager 30000 y supervisor 20000 z salesrep 20000 a sales rep 20000 b clerk 25000 c junior assistant 22000 x salesrep 20000 SQL> select distinct name from employee; NAME -------------------a b c x y z DML SELECTION with ● ● ● ● ● ● Between…and In Not in Like Relational Operators Logical Operators SQL> select * from cust; CNAME CID CADDR CACCNO CACCTYPE CBALANCE --------------- ---------- ---------- ---------- ---------- --------------------------------Anusha 1 Chennai 1001 savings 15000 Shriram 2 Pondy 1002 savings 25000 Chamundi 3 Salem 1003 fd 36200 Madhan 4 Salem 1004 checkings 5000 Subha 5 Trichy 1005 checkings 10000 Jayashree 6 Pondy 1006 fd 15000 Sridharan 7 Kanchi 1007 fd 22000 7 rows selected. SQL> select cname,caddr from cust where cbalance between 1000 and 10000; CNAME CADDR --------------- ---------Madhan Salem Subha Trichy SQL> select cname,cid,cacctype from cust where cacctype in ('savings','checkings','fd'); CNAME CID CACCTYPE --------------- ---------- ---------Anusha 1 savings Shriram 2 savings Chamundi 3 fd Madhan 4 checkings Subha 5 checkings Jayashree 6 fd Sridharan 7 fd 7 rows selected. SQL> select cname,cid,cacctype from cust where cacctype not in ('savings','checkings'); CNAME CID CACCTYPE --------------- ---------- ---------Chamundi 3 fd Jayashree 6 fd Sridharan 7 fd SQL> select cname,cbalance from cust where cname like '_a%an'; CNAME CBALANCE --------------- ---------Madhan 5000 SQL> select cname,cbalance from cust where cbalance>=15000; CNAME CBALANCE --------------- ---------Anusha 15000 Shriram 25000 Chamundi 36200 Jayashree 15000 Sridharan 22000 5 rows selected. SQL> select cname,cacctype,cbalance from cust where cbalance>20000 and CNAME CACCTYPE CBALANCE --------------- ---------- ---------- ---------- ---------- ---------Chamundi fd 36200 Sridharan fd 22000 2 rows selected. cacctype=’fd’;; 3) update Syntax for update Records from the table: SQL> update <<table name> set <columnane>=<value> where <column name=<value>; Query: SQL> update EMP SET SALARY=16000 WHERE EMPNO=101; 1 row updated. SQL> select * from emp; Empno ename designatin salary --------------------------------------101 x lecturer 16000 102 y lecturer 15000 103 104 z Asst. prof 30000 prof 45000 a UPDATE MULTIPLE COLUMNS Syntax for update multiple Records from the table: SQL> update <<table name> set <columnane>=<value> where <column name=<value>; Query: update emp set salary = 25000, designatin='asst. prof' where empno=102; 1 row updated. SQL> select * from emp; empno ename ---------- -----------101 x 102 y 103 z 104 a designatin ---------lecturer asst. prof asst. prof prof salary ---------16000 25000 20000 45000 4) DELETE Syntax for delete Records from the table: SQL> delete <table name> where <column name>=<value>; Query: SQL> delete emp where empno=103; 1 row deleted. SQL> select * from emp; empno ename designatin ---------- --------------------101 x lecturer 102 y asst. prof 104 a prof salary ---------16000 25000 45000 EX: NO: 3 TCL (TRANSACTION CONTROL LANGUAGE) Aim: To execute and verify the following Transaction Control Language commands and constraints ● COMMIT ● ROLL BACK ● SAVE POINT 1) SAVEPOINT Syntax for save point: SQL> SAVEPOINT <SAVE POINT NAME>; SQL> select * from stud; ROLLNO ---------110 200 NAME -------------------x z SALARY ---------20000 30000 SQL> insert into stud values(401,'cc',48000); 1 row created. SQL> insert into stud values(201,'aa',38000) 1 row created. SQL> insert into stud values(301,'b',36000) 1 row created. SQL> select * from stud; ROLLNO ---------110 200 401 201 301 501 NAME -------------------x z cc aa b dd SALARY ---------20000 30000 48000 38000 36000 46000 SQL> savepoint ss; Savepoint created. 2) ROLL BACK Rollback with savepoint Syntax: SQL> ROLL BACK <SAVE POINT NAME>; SQL> insert into stud values(666,'aaa',45000); 1 row created. SQL> select * from stud; ROLLNO NAME SALARY ---------- -------------------- ---------110 x 20000 200 z 30000 401 cc 201 aa 301 b 501 dd 666 aaa 48000 38000 36000 46000 45000 7 rows selected. SQL> rollback to ss; Rollback complete. SQL> select * from stud; ROLLNO NAME SALARY ---------- -------------------- ---------110 x 20000 200 z 30000 401 cc 48000 201 aa 38000 301 b 36000 501 dd 46000 6 rows selected. Rollback without savepoint select * from stud; ROLLNO ---------110 150 200 NAME -------------------x y z SALARY ---------20000 25000 30000 SQL> delete from stud where rollno=150; 1 row deleted. SQL> select * from stud; ROLLNO ---------110 200 NAME SALARY ----------------------------x 20000 z 30000 SQL> delete stud where rollno=110; 1 row deleted. SQL> select * from stud; ROLLNO ---------200 NAME -------------------z SALARY ---------30000 SQL> rollback; Rollback complete. SQL> select * from stud; ROLLNO ---------110 150 200 NAME -------------------x y z SALARY ---------20000 25000 30000 3) COMMIT Syntax for commit: SQL> COMMIT; QUERY: SQL> select * from stud; ROLLNO SALARY ------------------110 150 200 NAME -------------------x y z 20000 25000 30000 SQL> delete from stud where rollno=150; 1 row deleted. SQL> select * from stud; ROLLNO ---------110 200 NAME -------------------x z SALARY ---------20000 30000 SQL> commit; Commit complete. SQL> select * from stud; ROLLNO NAME ----------------------------110 x 200 z SALARY ---------20000 30000 SQL> rollback; Rollback complete. SQL> select * from stud; ROLLNO ---------110 200 NAME -------------------x z SALARY ---------20000 30000 EX: NO: 4 QUERIES NESTED QUERIES AND JOIN EX: NO: 4 A Nested Queries AIM To execute and verify the SQL commands for Nested Queries. OBJECTIVE: Nested Query can have more than one level of nesting in one single query. A SQL nested query is a SELECT query that is nested inside a SELECT, UPDATE, INSERT, or DELETE SQL query. PROCEDURE STEP 1: Start STEP 2: Create two different tables with its essential attributes. STEP 3: Insert attribute values into the table. STEP 4: Create the Nested query from the above created table. STEP 5: Execute Command and extract information from the tables. STEP 6: Stop SQL COMMANDS 1. COMMAND NAME: SELECT COMMAND DESCRIPTION: SELECT command is used to select records from the table. 2. COMMAND NAME: WHERE COMMAND DESCRIPTION: WHERE command is used to identify particular elements. 3. COMMAND NAME: HAVING COMMAND DESCRIPTION: HAVING command is used to identify particular elements. 4. COMMAND NAME: MIN (SAL) COMMAND DESCRIPTION: MIN (SAL) command is used to find minimum salary. Table -1 SYNTAX FOR CREATING A TABLE: SQL: CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE), COLUMN NAME.1 <DATATYPE> (SIZE) ……………………………); SQL> CREATE TABLE EMP2(EMPNO NUMBER(5), ENAME VARCHAR2(20), JOB VARCHAR2(20), SAL NUMBER(6), MGRNO NUMBER(4), DEPTNO NUMBER(3)); SYNTAX FOR INSERT RECORDS IN TO A TABLE: SQL :> INSERT INTO <TABLE NAME> VALUES< VAL1, 'VAL2',…..); INSERTION SQL> INSERT INTO EMP2 VALUES(1001,'MAHESH','PROGRAMMER',15000,1560,200); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1002,'MANOJ','TESTER',12000,1560,200); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1003,'KARTHIK','PROGRAMMER',13000,1400,201); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1004,'NARESH','CLERK',1400,1400,201); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1005,'MANI','TESTER',13000,1400,200); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1006,'VIKI','DESIGNER',12500,1560,201); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1007,'MOHAN','DESIGNER',14000,1560,201); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1008,'NAVEEN','CREATION',20000,1400,201); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1009,'PRASAD','DIR',20000,1560,202); 1 ROW CREATED. SQL> INSERT INTO EMP2 VALUES(1010,'AGNESH','DIR',15000,1400,200); 1 ROW CREATED. SYNTAX FOR SELECT RECORDS FROM THE TABLE: SQL> SELECT * FROM <TABLE NAME>; SQL> SELECT *FROM EMP2; EMPNO ---------1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 ENAME ---------MAHESH MANOJ KARTHIK NARESH MANI VIKI MOHAN NAVEEN PRASAD AGNESH JOB SAL ------------------PROGRAMMER TESTER PROGRAMMER CLERK TESTER DESIGNER DESIGNER CREATION DIR DIR MGRNO DPTNO ------------------15000 1560 200 12000 1560 200 13000 1400 201 1400 1400 201 13000 1400 200 12500 1560 201 14000 1560 201 20000 1400 201 20000 1560 202 15000 1400 200 TABLE- 2 SYNTAX FOR CREATING A TABLE: SQL: CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE), COLUMN NAME.1 <DATATYPE> (SIZE) ……………………………); SQL> CREATE TABLE DEPT2(DEPTNO NUMBER(3), DEPTNAME VARCHAR2(10), LOCATION VARCHAR2(15)); Table created. SYNTAX FOR INSERT RECORDS IN TO A TABLE: SQL :> INSERT INTO <TABLE NAME> VALUES< VAL1, 'VAL2',…..); INSERTION SQL> INSERT INTO DEPT2 VALUES(107,'DEVELOP','ADYAR'); 1 ROW CREATED. SQL> INSERT INTO DEPT2 VALUES(201,'DEBUG','UK'); 1 ROW CREATED. SQL> INSERT INTO DEPT2 VALUES(200,'TEST','US'); SQL> INSERT INTO DEPT2 VALUES(201,'TEST','USSR'); 1 ROW CREATED. SQL> INSERT INTO DEPT2 VALUES(108,'DEBUG','ADYAR'); 1 ROW CREATED. SQL> INSERT INTO DEPT2 VALUES(109,'BUILD','POTHERI'); 1 ROW CREATED. SYNTAX FOR SELECT RECORDS FROM THE TABLE: SQL> SELECT * FROM <TABLE NAME>; SQL> SELECT *FROM DEPT2; GENERAL SYNTAX FOR NESTED QUERY: SELECT "COLUMN_NAME1" FROM "TABLE_NAME1" WHERE "COLUMN_NAME2" [COMPARISON OPERATOR] (SELECT "COLUMN_NAME3" FROM "TABLE_NAME2" WHERE [CONDITION]) SYNTAX NESTED QUERY STATEMENT: SQL> SELECT <COLUMN_NAME> FROM FRORM <TABLE _1> WHERE <COLUMN_NAME> <RELATIONAL _OPERATION> 'VALUE' (SELECT (AGGRECATE FUNCTION) FROM <TABLE_1> WHERE <COLUMN NAME> = 'VALUE' (SELECT <COLUMN_NAME> FROM <TABLE_2> WHERE <COLUMN_NAME= 'VALUE')); NESTED QUERY STATEMENT: SQL> SELECT ENAME FROM EMP2 WHERE SAL> (SELECT MIN(SAL) FROM EMP2 WHERE DPTNO= (SELECT DEPTNO FROM DEPT2 WHERE LOCATION='UK')); Nested Query Output: ENAME ---------MAHESH MANOJ KARTHIK MANI VIKI EX: NO: 4 B - JOINS AIM To execute and verify the SQL commands using Join queries. OBJECTIVE: SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables. PROCEDURE STEP 1: Start STEP 2: Create the table with its essential attributes. STEP 3: Insert attribute values into the table STEP 4: Execute different Commands and extract information from the table. STEP 5: Stop SQL COMMANDS COMMAND NAME: INNER JOIN COMMAND DESCRIPTION: The INNER JOIN keyword return rows when there is at least one match in both tables. COMMAND NAME LEFT JOIN COMMAND DESCRIPTION: The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2). COMMAND NAME : RIGHT JOIN COMMAND DESCRIPTION: The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1). COMMAND NAME : FULL JOIN COMMAND DESCRIPTION: The FULL JOIN keyword return rows when there is a match in one of the tables. LEFT JOIN or LEFT OUTTER JOIN Table:1 - ORDERS SQL> CREATE table orders(O_Id number(5), Orderno number(5), P_Id number(3)); Table created. SQL> DESC orders; Name --------------------- Null? Type -------- ----------- O_ID NUMBER(5) ORDERNO NUMBER(5) P_ID NUMBER(3) INSERTING VALUES INTO ORDERS SQL> INSERT into orders values(&O_Id,&Orderno,&P_Id); Enter value for o_id: 1 Enter value for orderno: 77895 Enter value for p_id: 3 old 1: INSERT into orders values(&O_Id,&Orderno,&P_Id) new 1: INSERT into orders values(1,77895,3) 1 row created. SQL> INSERT into orders values(&O_Id,&Orderno,&P_Id); Enter value for o_id: 2 Enter value for orderno: 44678 Enter value for p_id: 3 old 1: INSERT into orders values(&O_Id,&Orderno,&P_Id) new 1: INSERT into orders values(2,44678,3) 1 row created. SQL> INSERT into orders values(&O_Id,&Orderno,&P_Id); Enter value for o_id: 3 Enter value for orderno: 22456 Enter value for p_id: 1 old 1: INSERT into orders values(&O_Id,&Orderno,&P_Id) new 1: INSERT into orders values(3,22456,1) 1 row created. SQL> INSERT into orders values(&O_Id,&Orderno,&P_Id); Enter value for o_id: 4 Enter value for orderno: 24562 Enter value for p_id: 1 old 1: INSERT into orders values(&O_Id,&Orderno,&P_Id) new 1: INSERT into orders values(4,24562,1) 1 row created. SQL> INSERT into orders values(&O_Id,&Orderno,&P_Id); Enter value for o_id: 5 Enter value for orderno: 34764 Enter value for p_id: 15 old 1: INSERT into orders values(&O_Id,&Orderno,&P_Id) new 1: INSERT into orders values(5,34764,15) 1 row created. TABLE SECTI ON: SQL> SELECT * FROM orders; O_ID ORDERNO P_ID ---------- ------------------- 1 2 3 4 5 77895 3 44678 3 22456 1 24562 1 34764 15 TABLE -2: PERSONS SQL> CREATE table persons(p_Id number(5), LASTNAME varchar2(10), Firstname varchar2(15), Address varchar2(20), city varchar2(10)); Table created. SQL> INSERT into persons values(&p_Id,'&Lastname','&firstname','&Address','&city'); Enter value for p_id: 1 Enter value for lastname: Hansen Enter value for firstname: Ola Enter value for address: Timoteivn 10 Enter value for city: sadnes old 1: INSERT into persons values(&p_Id,'&Lastname','&firstname','&Address','&city') new 1: INSERT into persons values(1,'Hansen','Ola','Timoteivn 10','sadnes') 1 row created. SQL> INSERT into persons values(&p_Id,'&Lastname','&firstname','&Address','&city'); Enter value for p_id: 2 Enter value for lastname: Svendson Enter value for firstname: Tove Enter value for address: Borgn 23 Enter value for city: Sandnes old 1: INSERT into persons values(&p_Id,'&Lastname','&firstname','&Address','&city') new 1: INSERT into persons values(2,'Svendson','Tove','Borgn 23','Sandnes') 1 row created. SQL> INSERT into persons values(&p_Id,'&Lastname','&firstname','&Address','&city'); Enter value for p_id: 3 Enter value for lastname: Pettersen Enter value for firstname: Kari Enter value for address: Storgt 20 Enter value for city: Stavanger old 1: INSERT into persons values(&p_Id,'&Lastname','&firstname','&Address','&city') new 1: INSERT into persons values(3,'Pettersen','Kari','Storgt 20','Stavanger') 1 row created. SQL> SELECT * FROM persons; P_ID LASTNAME FIRSTNAME ---------- 1 2 3 ------------------Hansen sandnes Svendson Sandnes Pettersen Stavanger --------------- ADDRESS CITY ------------------- Ola Timoteivn 10 Tove Borgn 23 Kari Storgt 20 LEFT JOIN SYNTAX SQL> SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name LEFT JOIN EXAMPLE SQL> SELECT persons.lastname,persons.firstname,orders.orderno FROM persons LEFT JOIN rders ON persons.p_Id = orders.p_Id ORDER BY persons.lastname; OUTPU T LASTNAME FIRSTNAME ORDERNO ------------------ -------------------------------Hansen Ola Hansen Ola Pettersen Kari Pettersen Kari Svendson Tove 22456 2 4 5 6 2 7 7 8 9 5 4 4 6 7 8 F U L L O U T T E R J O I N SQL> SELECT * FROM persons; P_ID LASTNAME FIRSTNAME ADDRESS CITY ---------- --------------- -------------------------------------------1 Hansen Ola Timoteivn 10 sandnes 2 Svendson Tove Borgn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger SQL> SELECT * FROM orders; P _ O_ID I ---------D 1 2 3 ORDERNO ---------77895 44678 22456 3 3 1 FULL OUTER JOIN SYNTAX SQL>SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name FULL OUTER JOIN EXAMPLE SQL> SELECT persons.lastname,persons.firstname,orders.orderno FROM persons FULL OUTER JOIN orders ON persons.p_Id = orders.p_Id ORDER BY persons.lastname; RIGHT OUTTER JOIN RIGHT OUTTER JOIN SYNTAX SQL>SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName RIGHT OUTTER JOIN EXAMPLE SQL> SELECT persons.lastname,persons.firstname,orders.orderno FROM persons RIGHT OUTER JOIN orders ON persons.p_Id = orders.p_Id ORDER BY persons.lastname; LASTNAME FIRSTNAME ORDERNO ------------------- -------------------------------Hansen Ola 24562 Hansen Ola 22456 Pettersen Kari 44678 Pettersen Kari 77895 INNER JOIN INNTER JOIN SYNTAX SQL>SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name INNTER JOIN EXAMPLE SQL> SELECT persons.lastname,persons.firstname,orders.orderno 2 FROM persons 3 INNER JOIN orders 4 ON persons.p_Id = orders.p_Id 5 ORDER BY persons.lastname; LASTNAME FIRSTNAME ORDERNO ------------------ -------------------------------Hansen Ola 22456 Hansen Ola 24562 Pettersen Kari 77895 Pettersen Kari 44678 LASTNAME FIRSTNAME ORDERNO ------------Hansen Hansen Pettersen Pettersen Svendson 6 rows selected. --------------Ola Ola Kari Kari Tove ---------2 2 4 5 6 2 4 5 6 2 7 7 8 9 5 4 4 6 7 8 3 4 7 6 4 EX: NO: 5 VIEWS AI M To execute and verify the SQL commands for Views. OBJECTIVE : • • • Views Helps to encapsulate complex query and make it reusable. Provides user security on each view - it depends on your data policy security. Using view to convert units - if you have a financial data in US currency, you can create view to convert them into Euro for viewing in Euro currency. PROCEDUR E STEP 1: Start STEP 2: Create the table with its essential attributes. STEP 3: Insert attribute values into the table. STEP 4: Create the view from the above created table. STEP 5: Execute different Commands and extract information from the View. STEP 6: Stop .SQL COMMANDS 1. COMMAND NAME: CREATE VIEW COMMAND DESCRIPTION: CREATE VIEW command is used to define a view. 2. COMMAND NAME: INSERT IN VIEW COMMAND DESCRIPTION: INSERT command is used to insert a new row into the view. 3. COMMAND NAME: DELETE IN VIEW COMMAND DESCRIPTION: DELETE command is used to delete a row from the view. 4. COMMAND NAME: UPDATE OF VIEW COMMAND DESCRIPTION: UPDATE command is used to change a value in a tuple without changing all values in the tuple. 5. COMMAND NAME: DROP OF VIEW COMMAND DESCRIPTION: DROP command is used to drop the view table COMMANDS EXECUTION CREATION OF TABLE ------------------------------SQL> CREATE TABLE EMPLOYEE ( EMPLOYEE_NAMEVARCHAR2(10), EMPLOYEE_NONUMBER(8) , DEPT_NAME VARCHAR2(10), DEPT_NO NUMBER (5),DATE_OF_JOIN DATE); Table created. TABLE DESCRIPTION ------------------------------SQL> DESC EMPLOYEE; NAME NULL? ------------------------------- -------- -----------------------EMPLOYEE_NAME EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_JOIN T Y P E VAR CH AR2 (10) N U M B E R ( 8 ) VAR CHA R2(1 0) N U M B E R ( 5 ) D A T E SUNTAX FOR CREATION OF VIEW -------------------------------------------------SQL> CREATE <VIEW> <VIEW NAME> AS SELECT <COLUMN_NAME_1>, <COLUMN_NAME_2> FROM <TABLE NAME>; CREATION OF VIEW -----------------------------SQL> CREATE VIEW EMPVIEW AS SELECT EMPLOYEE_NAME,EMPLOYEE_NO,DEPT_NAME,DEPT_NO,DATE_OF_JOIN FROM EMPLOYEE ; VIEW CREATED. DESCRIPTION OF VIEW -------------------------------- SQL> DESC EMPVIEW; NAME NULL? TYPE ----------------------------------------- -------- ---------------------------EMPLOYEE_NAME VARCHAR2(10) EMPLOYEE_NO NUMBER(8) DEPT_NAME VARCHAR2(10) DEPT_NO NUMBER(5) DISPLAY VIEW: ---------------------SQL> SELECT * FROM EMPVIEW; EMPLOYEE_N EMPLOYEE_NO DEPT_NAME ---------- ----------- ---------- ---------RAVI 124 ECE 345 CSE VIJAY 98 IT RAJ 100 CSE GIRI DEPT_NO 8 9 2 1 2 2 6 7 I N S E R T I O N I N T O V I E W - INSERT STATEMENT: SYNTAX: SQL> INSERT INTO <VIEW_NAME> (COLUMN NAME1,………) VALUES(VALUE1,….); SQL> INSERT INTO EMPVIEW VALUES ('SRI', 120,'CSE', 67,'16-NOV-1981'); 1 ROW CREATED. SQL> SELECT * FROM EMPVIEW; EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO ---------- ----------- ---------- ---------RAVI 124 ECE 89 VIJAY 345 CSE 21 RAJ 98 IT 22 GIRI 100 CSE 67 SRI 120 CSE 67 SQL> SELECT * FROM EMPLOYEE; EMPLOYEE_N EMPLOYEE_NO DEPT_NAME ---------- ----------- ---------- ---------- --------RAVI 124 ECE 345 CSE VIJAY 98 IT RAJ 100 CSE 120 CSE GIRI SRI DEPT_NO DATE_OF_J 8 9 1 5 J U N 0 5 2 1 2 1 J U N 0 6 O 2 V D 2 E 3 8 L 0 1 E 6 T S 7 I E 1 O P 6 N O 0 N F 6 O V 6 V I 7 E 1 8 W 4 1 : N DELETE STATEMENT: SYNTAX: SQL> DELETE <VIEW_NMAE>WHERE <COLUMN NMAE> ='VALUE'; SQL> DELETE FROM EMPVIEW WHERE EMPLOYEE_NAME='SRI'; 1 ROW DELETED. SQL> SELECT * FROM EMPVIEW; EMPLOYEE_N EMPLOYEE_NO DEPT_NAME ---------- ----------- ---------- ---------RAVI 124 ECE 89 VIJAY 345 CSE 21 RAJ 98 IT 22 GIRI 100 CSE 67 DEPT_NO UPDATE STATEMENT: SYNTAX: AQL>UPDATE <VIEW_NAME> SET< COLUMN NAME> = <COLUMN NAME> +<VIEW> WHERE <COLUMNNAME>=VALUE; SQL> UPDATE EMPKAVIVIEW SET EMPLOYEE_NAME='KAVI' WHERE EMPLOYEE_NAME='RAVI'; 1 ROW UPDATED. SQL> SELECT * FROM EMPKAVIVIEW; EMPLOYEE_N EMPLOYEE_NO DEPT_NAME ---------- ----------- ---------- ---------KAVI 124 ECE 89 VIJAY 345 CSE 21 RAJ 98 IT 22 GIRI 100 CSE 67 DROP A VIEW: SYNTAX: SQL> DROP VIEW <VIEW_NAME> EXAMPLE SQL>DROP VIEW EMPVIEW; VIEW DROPED CREATE A VIEW WITH SELECTED FIELDS: SYNTAX: DEPT_NO SQL>CREATE [OR REPLACE] VIEW <VIEW NAME>AS SELECT <COLUMN NAME1>…..FROM <TABLE ANME>; EXAMPLE-2 : SQL> CREATE OR REPLACE VIEW EMPL_VIEW1 AS SELECT EMPNO, ENAME, SALARY FROM EMPL; SQL> SELECT * FROM EMPL_VIEW1; EXAMPLE-3 : SQL> CREATE OR REPLACE VIEW EMPL_VIEW2 AS SELECT * FROM EMPL WHERE DEPTNO=10; SQL> SELECT * FROM EMPL_VIEW2; Note: Replace is the keyboard to avoid the error "ora_0095:name is already used by an existing abject". CHANGING THE COLUMN(S) NAME M THE VIEW DURING AS SELECT STATEMENT: TYPE-1: SQL> CREATE OR REPLACE VIEW EMP_TOTSAL(EID,NAME,SAL) AS SELECT EMPNO,ENAME,SALARY FROM EMPL; View created. EMPNO ENAME SALARY ---------- -------------------- ---------- ---------7369 SMITH 7499 1000 1050 MARK 7565 WILL 1500 1800 1500 7678 JOHN 7578 1500 TOM 7548 TURNER 6 rows selected. View created. SALARY EMPNO ENAME M G R N O DE PT N O ---------- -------------------- ---------- ---------- ---------------------------7578 TOM 1500 7298 10 7548 TURNER 1500 7298 10 View created. SQL> SELECT * FROM EMP_TOTSAL; TYPE-2: SQL> CREATE OR REPLACE VIEW EMP_TOTSAL AS SELECT EMPNO "EID",ENAME "NAME",SALARY "SAL" FROM EMPL; SQL> SELECT * FROM EMP_TOTSAL; EXAMPLE FOR JOIN VIEW: TYPE-3: SQL> CREATE OR REPLACE VIEW DEPT_EMP AS SELECT A.EMPNO "EID",A.ENAME "EMPNAME",A.DEPTNO "DNO",B.DNAM E "D_NAME",B.LOC "D_LOC" FROM EMPL A,DEPMT B WHERE A.DEPTNO=B.DEPTNO; SQL> SELECT * FROM DEPT_EMP; EID NAME SAL ---------- -------------------- ---------- ---------7369 SMITH 7499 MARK 7565 WILL 7678 JOHN 7578 TOM 7548 TURNER 6 rows selected. 1 0 0 0 1 0 5 0 1 5 0 0 1 8 0 0 1 5 0 0 1 View created. EID NAME 5 0 0 S A L ---------- -------------------- ---------- ---------7369 SMITH 7499 1000 1050 MARK 7565 WILL 7678 1500 1800 1500 JOHN 7578 TOM 1500 7548 TURNER 6 rows selected. View created. EID EMPNAME DNO D _ N A M E D _ L O C ---------- -------------------- ---------- ---------- -----------------------7578 TOM 10 ACCOUNT NEW YORK 7548 TURNER 10 ACCOUNT NEW YORK 7369 SMITH 20 SALES CHICAGO 7678 JOHN 20 SALES CHICAGO 7499 MARK 30 RESEARCH ZURICH 7565 WILL 30 RESEARCH ZURICH VIEW READ ONLY AND CHECK OPTION: READ ONLY CLAUSE: You can create a view with read only option which enable other to only query .no dml operation can be performed to this type of a view. EXAMPLE-4 : SQL>CREATE OR REPLACE VIEW EMP_NO_DML AS SELECT * FROM EMPL WITH READ ONLY; WITH CHECK OPTION CLAUSE EXAMPLE4: SQL> CREATE OR REPLACE VIEW EMP_CK_OPTION AS SELECT EMPNO,ENAME,SALARY,DEPTNO FROM EMPL WHERE DEPTNO =10 WITH CHECK OPTION; SQL> SELECT * FROM EMP_CK_OPTION; JOIN VIEW: EXAMPLE-5: SQL> CREATE OR REPLACE VIEW DEPT_EMP_VIEW AS SELECT A.EMPNO, A.ENAME, A.DEPTNO, B.DNAME, B.LOC FROM EMPL A,DEPMT B WHERE A.DEPTNO=B.DEPTNO; SQL> SELECT * FROM DEPT_EMP_VIEW; View created. EMPNO ENAME SALARY DEPTNO ---------- -------------------- ---------- ---------7578 TOM 1500 10 7548 TURNER 1500 10 View created. EMPNO ENAME DEPTNO DNAME LOC ------------------------------ -------------------- ---------- -------------------7578 TOM 10 ACCOUNT NEW YORK 7548 TURNER 10 ACCOUNT NEW YORK 7369 SMITH 20 SALES CHICAGO 7678 JOHN 20 SALES CHICAGO 7499 MARK 30 RESEARCH ZURICH 7565 WILL 30 RESEARCH ZURICH 6 rows selected. RESULT: Thus the SQL commands for View has been verified and executed successfully. EX. NO: 6 SINGLE ROW FUNCTIONS 🗹 Character Functions 🗹 Number Functions 🗹 Date Functions SQL> DESC EMPLOYEE22; Name Null? Type ----------------------------------------- -------- ----------------------ENO NOT NULL NUMBER(5) ENAME VARCHAR2(50) DEPTID NUMBER(3) SALARY NUMBER(7) JOB VARCHAR2(5) MGRID NUMBER(3) COM VARCHAR2(6) SQL> select * from employee22; ENO 1 2 3 4 5 ENAME x y z a b DEPTID 10 20 20 30 40 SALARY 100000 50000 25000 15000 10000 JOB MD Mgr Mgr Mgr Emp MGRID 0 1 2 2 3 COM 15 10 2 1 5 SQL> select * from employee22 where LOWER(ename)='x'; ENO 1 ENAME X DEPTID SALARY JOB MGRID 10 100000 MD 0 COM 15 SQL> select * from employee22 where UPPER(ename)='y'; no rows selected SQL> select * from employee22 where UPPER(ename)='Y'; ENO 2 ENAME y DEPTID 20 SALARY 50000 JOB MGRID Mgr SQL> select 'Salary of ' || ename || ' is ' || salary from employee22; 'SALARYOF'||ENAME||'IS'||SALARY -------------------------------------------------------------------------Salary of X is 100000 Salary of y is 50000 Salary of z is 25000 Salary of a is 15000 Salary of b is 10000 1 COM 10 SQL> select * from employee22 where LOWER(ename)='x'; ENO ENAME DEPTID 1 X 10 SALARY 100000 JOB MGRID MD COM 0 15 SQL> select * from employee22 where UPPER(ename)='y'; no rows selected SQL> select * from employee22 where UPPER(ename)='Y'; ENO 2 ENAME y DEPTID 20 SALARY 50000 JOB MGRID Mgr 1 COM 10 SQL> select 'Salary of ' || ename || ' is ' || salary from employee22; 'SALARYOF'||ENAME||'IS'||SALARY -------------------------------------------------------------------------------Salary of X is 100000 Salary of y is 50000 Salary of z is 25000 Salary of a is 15000 Salary of b is 10000 SQL> create table sample(name varchar2(30),fname varchar2(10),lname varchar2(10)); Table created. SQL> desc sample Name Null? Type ----------------------------------------- -------- ---------------------------NAME VARCHAR2(30) FNAME VARCHAR2(10) LNAME VARCHAR2(10) SQL> alter table sample add(fno float(10)); Table altered. SQL> desc sample Name Null? Type ----------------------------------------- -------- ---------------------------NAME VARCHAR2(30) FNAME VARCHAR2(10) LNAME VARCHAR2(10) FNO FLOAT(10) SQL> insert into sample values('Hello world','Lovelyn','Divya',120.856); 1 row created. SQL> insert into sample values('Welcome everyone','Dhivyaa','Meens',340.15); 1 row created. SQL> insert into sample values('Hi everybody','Harsha','Innanji',280.59); 1 row created. SQL> select * from sample; NAME FNAME LNAME FNO ------------------------------ ---------- ---------- ------------------------------Hello world Lovelyn Divya 120.9 Welcome everyone Dhivyaa Meens 340.2 Hi everybody Harsha Innanji 280.6 SQL> select concat(fname,lname),fno from sample; CONCAT(FNAME,LNAME) FNO -------------------- --------------------------------LovelynDivya 120.9 DhivyaaMeens 340.2 HarshaInnanji 280.6 SQL> select upper(name) from sample; UPPER(NAME) -----------------------------HELLO WORLD WELCOME EVERYONE HI EVERYBODY SQL> select lower(lname) from sample; LOWER(LNAME) ---------divya meens innanji SQL> select substr(fname,1,5) from sample; SUBST ------------Lovel Dhivy Harsh SQL> select length(name) from sample; LENGTH(NAME) ------------------------11 16 12 SQL> select length(lname) from sample; LENGTH(LNAME) ------------5 5 7 SQL> select name,instr(name,1) from sample; NAME INSTR(NAME,1) ------------------------------ ---------------------Hello world 0 Welcome everyone 0 Hi everybody 0 SQL> select name,instr(name,'e',1) from sample; NAME INSTR(NAME,'E',1) ------------------------------ ----------------Hello world 2 Welcome everyone 2 Hi everybody 4 SQL> select fname,instr(fname,'a') from sample; FNAME INSTR(FNAME,'A') ---------- ----------------------------------Lovelyn 0 Dhivyaa 6 Harsha 2 SQL> select lpad(lname,10,'*') from sample; LPAD(LNAME) -----------------*****Divya *****Meens ***Innanji SQL> select rpad(fname,10,'*')from sample; RPAD(FNAME) ---------Lovelyn*** Dhivyaa*** Harsha**** SQL> select trim('d' from 'dhivyaa')from sample; TRIM(' -----hivyaa hivyaa hivyaa SQL> select trim('d' from 'dhivyaa')from sample where fno=340.2; TRIM(' -----hivyaa SQL> select trim('a' from fname)from sample; TRIM('A'FR ---------Lovelyn Dhivy Harsh NUMBER FUNCTIONS: SQL> select ROUND(45.923,2),ROUND(45.923,0),ROUND(45.923,-1) from DUAL; ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1) --------------- --------------- ---------------------------------------------------------45.92 46 50 SQL> select trunc(45.923,2),trunc(45.923),trunc(45.923,-2) from DUAL; TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-2) --------------- ------------- ------------------------------------------------------45.92 45 0 SQL> desc sample Name Null? Type ----------------------------------------- -------- ---------------------------NAME VARCHAR2(30) FNAME VARCHAR2(10) LNAME VARCHAR2(10) FNO FLOAT(10) HIREDATE DATE SQL> insert into sample values('REC CSE','Anitha','Anu',320.7,'21-mar-88'); 1 row created. SQL> insert into sample values('Hi chennai','aishwarya','sukumar',170,'30-oct-87'); 1 row created. SQL> select * from sample; NAME FNAME LNAME FNO HIREDATE ------------------------------ ---------- ---------- ---------- ------------------------------------Hello world Lovelyn Divya 120.9 Welcome everyone Dhivyaa Meens 340.2 Hi everybody Harsha Innanji 280.6 REC CSE Anitha Anu 320.7 21-MAR-88 Hi chennai aishwarya sukumar 170 30-OCT-87 SQL> select lname,hiredate from sample where lname like 'a%'; no rows selected SQL> select lname,hiredate from sample where lname like 'A%'; LNAME HIREDATE ---------- --------------------------Anu 21-MAR-88 SQL> select sysdate from DUAL; SYSDATE ----------------22-AUG-07 SQL> select fname,(sysdate-hiredate)/7 as weeks from sample where fno=170; FNAME WEEKS ---------- ---------aishwarya 1033.78013 SQL> select fname,hiredate,months_between(sysdate,hiredate) from sample where fno=320.7; FNAME HIREDATE MONTHS_BETWEEN(SYSDATE,HIREDATE) ---------- --------- ----------------------------------------------------------------------Anitha 21-MAR-88 233.047329 SQL> select fname,hiredate,add_months(hiredate,6),next_day(hiredate,'friday'),last_day (hiredate) from sample; FNAME HIREDATE ADD_MONTH NEXT_DAY( LAST_DAY( ---------- --------- --------- --------- --------------------------------------------------Lovelyn Dhivyaa Harsha Anitha 21-MAR-88 21-SEP-88 25-MAR-88 31-MAR-88 aishwarya 30-OCT-87 30-APR-88 06-NOV-87 31-OCT-87 SQL> select fname ,hiredate,round(hiredate,'Month'),trunc(hiredate,'month') from sample where fno=170; FNAME HIREDATE ROUND(HIR TRUNC(HIR ---------- --------- --------- ----------------------------------------aishwarya 30-OCT-87 01-NOV-87 01-OCT-87 EX. NO:7 MULTIROW FUNCTIONS 🗹 Order By 🗹 Group By 🗹 Aggregate Functions SQL> select * from cust; CNAME CID CADDR CACCNO CACCTYPE CBALANCE --------------- ---------- ---------- ---------- ---------- ------------------------------------------Anusha 1 Chennai 1001 savings Shriram 2 Pondy 1002 savings Chamundi 3 Salem 1111 fd Madhan 4 Salem 1004 checkings Subha 5 Trichy 1005 checkings Jayashree 6 Pondy 1006 fd Sridharan 7 Kanchi 1007 fd 15000 25000 36200 5000 10000 15000 22000 ORDER BY ======== SQL> select cname from cust order by cname desc; CNAME --------------Subha Sridharan Shriram Madhan Jayashree Chamundi Anusha 7 rows selected. SQL> select cname,caccno,cbalance from cust order by cbalance desc,cname asc; CNAME CACCNO CBALANCE --------------- ---------- -------------------------Chamundi 1003 36200 Shriram 1002 25000 Sridharan 1007 22000 Anusha 1001 15000 Jayashree 1006 15000 Subha 1005 10000 Madhan 1004 5000 7 rows selected. GROUP BY ========= SQL> select max(cbalance),cacctype from cust group by cacctype; MAX(CBALANCE) CACCTYPE ------------- ---------25000 savings 10000 checkings 36200 fd AGGREGATE FUNCTIONS ======================= SQL> select count(*) from cust; COUNT(*) ---------7 SQL> select count(distinct cname) from cust; COUNT(CNAME) -----------7 SQL>select sum(cbalance) as totbal,avg(sum(cbalance)) as average from cust where cacctype='savings'; TOTBAL AVERAGE ----------------------------40000 20000 SQL> select max(cbalance),min(cbalance) from cust; MAX(CBALANCE) MIN(CBALANCE) ----------------------------------------------------36200 5000 EX: NO: 8 Sequences, Index, Synonym A sequence is a user-defined schema bound object that generates a sequence of numeric values according to the specification with which the sequence was created. The sequence of numeric values is generated in an ascending or descending order at a defined interval and can be configured to restart (cycle) when exhausted. Sequences, unlike identity columns, are not associated with specific tables. Applications refer to a sequence object to retrieve its next value. The relationship between sequences and tables is controlled by the application. User applications can reference a sequence object and coordinate the values across multiple rows and tables. Syntax: CREATE SEQUENCE [schema_name . ] sequence_name [ AS [ built_in_integer_type | user-defined_integer_type ] ] [ START WITH <constant> ] [ INCREMENT BY <constant> ] [ { MINVALUE [ <constant> ] } | { NO MINVALUE } ] [ { MAXVALUE [ <constant> ] } | { NO MAXVALUE } ] [ CYCLE | { NO CYCLE } ] [ { CACHE [ <constant> ] } | { NO CACHE } ] [;] Example: CREATE SEQUENCE customers_seq START WITH 1000 INCREMENT BY 1 NOCACHE NOCYCLE; Creating an Index Explicitly CREATE INDEX emp_ename ON emp(ename) TABLESPACE users STORAGE (INITIAL 20K NEXT 20k PCTINCREASE 75); DROP INDEX Statement DROP INDEX index_name CREATE SYNONYMS: CREATE SYNONYM statement is used to create a synonym, which is an alternative name for a table, view, sequence, procedure, stored function, package, materialized view, Java class schema object, user-defined object type, or another synonym. Syntax: CREATE SYNONYM offices FOR hr.locations; Public Synonym: CREATE PUBLIC SYNONYM emp_table FOR hr.employees@remote.us.oracle.com; Ex. No : 09 PROGRAMS SIMPLE PL/SQL Aim : To work with different PL/SQL programs 1) SQL> set serveroutput on SQL> declare 2 a number; 3 b number; 4 c number; 5 begin 6 a:=&a; 7 b:=&b; 8 c:=a+b; 9 dbms_output.put_line('sum of'||a||'and'||b||'is'||c); 10 end; 11 / Enter value for a: 5 old 6: a:=&a; new 6: a:=5; Enter value for b: 5 old 7: b:=&b; new 7: b:=5; sum of5and5is10 PL/SQL procedure successfully completed. 2) Finding the MAXIMUM NO SQL> set serveroutput on SQL> declare 2 a number; 3 b number; 4 c number; 5 d number; 6 begin 7 dbms_output.put_line('enter a:'); 8 a:=&a; 9 dbms_output.put_line('enter b:'); 10 b:=&b; 11 dbms_output.put_line('enter c:'); 12 c:=&b; 13 if(a>b)and(a>c) then 14 dbms_output.put_line('A is maximum'); 15 elsif(b>a)and(b>c)then 16 dbms_output.put_line('B is maximum'); 17 else 18 dbms_output.put_line('C is maximum'); 19 end if; 20* end; 21 / Enter value for a: 9 old 8: a:=&a; new 8: a:=9; Enter value for b: 6 old 10: b:=&b; new 10: b:=6; Enter value for c: 10 old 12: c:=&b; new 12: c:=10; enter a: enter b: enter c: C is maximum PL/SQL procedure successfully completed. 3) REVERSING THE NO SQL> set serveroutput on SQL> declare 2 given_number varchar(5):='1234'; 3 str_length number(2); 4 inverted_number varchar(5); 5 begin 6 str_length:=length(given_number); 7 for cntr in reverse 1..str_length 8 loop 9 inverted_number:=inverted_number||substr(given_number,cntr,1); 10 end loop; 11 dbms_output.put_line('the given no is'||given_number); 12 dbms_output.put_line('the inverted number is'|| inverted_number); 13* end; 14 / the given no is1234 the inverted number is4321 PL/SQL procedure successfully completed. Ex.No 10: CONTROL STRCTURE Aim: To write a PL/SQL block using different control (if, if else, for loop, while loop,…) statements. OBJECTIVE: PL/SQL Control Structure provides conditional tests, loops, flow control and branches that let to produce well-structured programs. SQL Program for IF Condition: 1. Write a PL/SQL Program using if condition PROCEDURE STEP 1: Start STEP 2: Initialize the necessary variables. STEP 3: invoke the if condition. STEP 4: Execute the statements. STEP 5: Stop. PL/ SQL GENERAL SYNTAX FOR IF CONDITION: SQL> DECLARE <VARIABLE DECLARATION>; BEGIN IF(CONDITION)THEN <EXECUTABLE STATEMENT >; END; 2) PL/ SQL GENERAL SYNTAX FOR IF AND ELSECONDITION: SQL> DECLARE <VARIABLE DECLARATION>; BEGIN IF (TEST CONDITION) THEN <STATEMENTS>; ELSE <STATEMENTS>; ENDIF; END; Less then or Greater Using IF ELSE SQL> declare n number; begin dbms_output. put_line('enter a number'); n:=&number; if n<5 then dbms_output.put_line('entered number is less than 5'); else dbms_output.put_line('entered number is greater than 5'); end if; end; Input Enter value for number: 2 old 5: n:=&number; new 5: n:=2; Output: entered number is less than 5 PL/SQL procedure successfully completed. 3) PL/ SQL GENERAL SYNTAX FOR LOOPING STATEMENT: SQL> DECLARE <VARIABLE DECLARATION>; BEGIN LOOP <STATEMENT>; END LOOP; <EXECUTAVLE STATEMENT>; END; SUMMATION OF ODD NUMBERS USING FOR LOOP SQL> declare n number; sum1 number default 0; endvalue number; begin endvalue:=&endvalue; n:=1; for n in 1..endvalue loop if mod(n,2)=1 then sum1:=sum1+n; end if; end loop; dbms_output.put_line('sum ='||sum1); end; / INPUT: Enter value for endvalue: 4 old 6: endvalue:=&endvalue; new 6: endvalue:=4; OUTPUT: sum =4 PL/SQL procedure successfully completed. 4) PL/ SQL GENERAL SYNTAX FOR LOOPING STATEMENT: SQL> DECLARE <VARIABLE DECLARATION>; BEGIN WHILE <condition> LOOP <STATEMENT>; END LOOP; <EXECUTAVLE STATEMENT>; END; *********SUMMATION OF ODD NUMBERS USING WHILE LOOP********** SQL> declare n number; sum1 number default 0; endvalue number; begin endvalue:=&endvalue; n:=1; while(n<endvalue) loop sum1:=sum1+n; n:=n+2; end loop; dbms_output.put_line('sum of odd no. bt 1 and' ||endvalue||'is'||sum1); end; INPUT: Enter value for endvalue: 4 old 6: endvalue:=&endvalue; new 6: endvalue:=4; OUTPUT: sum of odd no. bt 1 and4is4 PL/SQL procedure successfully completed. RESULT: Thus the PL/SQL block for different controls are verified and executed. EX: NO: 11 PROCEDURES AIM To write a PL/SQL block to display the student name, marks whose average mark is above 60%. Algorithm: STEP1:Start STEP2:Create a table with table name stud_exam STEP3:Insert the values into the table and Calculate total and average of each student STEP4: Execute the procedure function the student who get above 60%. STEP5: Display the total and average of student STEP6: End PROCEDURE FOR GCD NUMBERS III) PROGRAM: SQL> create or replace procedure pro is a number(3); b number(3); c number(3); d number(3); begin a:=&a; b:=&b; if(a>b) then c:=mod(a,b); if(c=0) then dbms_output.put_line('GCD is'); dbms_output.put_line(b); else dbms_output.put_line('GCD is'); dbms_output.put_line(c); end if; else d:=mod(b,a); if(d=0) then 81 dbms_output.put_line('GCD is'); dbms_output.put_line(a); else dbms_output.put_line('GCD is'); dbms_output.put_line(d); end if; end if; end; / Enter value for a: 8 old 8: a:=&a; new 8: a:=8; Enter value for b: 16 old 9: b:=&b; new 9: b:=16; Procedure created. SQL> set serveroutput on; SQL> execute pro; GCD is 8 PL/SQL procedure successfully completed. RESULT: Thus the PL/SQL procedures are executed. 82 EX: NO: 12 FUNCTIONS AIM To write a Functional procedure to search an address from the given database. SQL> create table stud(rno number(2),mark1 number(3),mark2 number(3),total number(3),primary key(rno)); Table created. SQL> desc stud; Name Null? Type ----------------------------------------- -------- ---------------------------RNO NOT NULL NUMBER(2) MARK1 NUMBER(3) MARK2 NUMBER(3) TOTAL NUMBER(3) SQL> select * from stud; RNO MARK1 MARK2 TOTAL ---------- ---------- ---------- -----------------1 80 85 0 83 2 3 4 75 65 90 84 80 85 0 0 0 SQL> create or replace function stude(rnum number) return number is 2 total number; 3 m1 number; 4 m2 number; 5 begin 6 select mark1,mark2 into m1,m2 from stud where rno=rnum; 7 total:=m1+m2; 8 return total; 9 end; 10 / Function created. SQL> select stude(2) from dual; STUDE(2) ---------159 SQL> create table purchase (icode number(3),iname varchar2(13),price number(6),quantity number(3),rate number(8),primary key(icode),unique(iname)); Table created. SQL> desc purchase; Name Null? Type ----------------------------------------- -------- ---------------------------ICODE NOT NULL NUMBER(3) INAME VARCHAR2(13) PRICE NUMBER(6) QUANTITY NUMBER(3) RATE NUMBER(8) SQL> select * from purchase; ICODE INAME PRICE QUANTITY RATE ---------- -------------------- ---------- ------------------- ---------100 PenSet 20 10 0 101 ParkerPen 60 10 0 102 180pg Note 24 10 0 103 80pg Note 10 25 0 104 StickFile 10 20 0 84 SQL> create or replace function pur(itmcd number) return number is 2 qt number; 3 pr number; 4 rate number; 5 begin 6 select price,quantity into pr,qt from purchase where icode=itmcd; 7 rate:=qt*pr; 8 return rate; 9 end; 10 / Function created. SQL> select pur(102) from dual; PUR(102) ----------240 RESULT:Thus the Function for searching process has been executed successfully. Ex NO : 13 Cursors Aim : To work with PL/SQL cursors. Implicit Cursors Following are the cursor attributes available ● SQL%ROWCOUNT – Number of rows returned/changed in the last executed query. Applicable for SELECT as well as DML statement ● SQL%ISOPEN – Boolean TRUE if the cursor is still open, else FALSE. For implicit cursor it is FALSE only ● SQL%FOUND – Boolean TRUE, if the cursor fetch points to a record, else FALSE ● SQL%NOTFOUND – Inverse of SQL%FOUND. The flag is set as FALSE when the cursor pointer does not point to a record in the result set. DECLARE L_SAL NUMBER; BEGIN SELECT SALARY INTO L_SAL FROM EMPLOYEES 85 WHERE EMPLOYEE_ID=110; DBMS_OUTPUT.PUT_LINE(‘Salary for KING is : ’||TO_CHAR(L_SAL)); END; Explicit Cursor These cursors are explicitly declared in the DECLARE section of the block. They possess a specific name and a static SELECT statement attached to them. Explicit cursors are manually executed by the developers and follow complete execution cycle. Attributes: ● ● ● ● CURSOR%ROWCOUNT CURSOR%ISOPEN CURSOR%FOUND CURSOR%NOTFOUND Cursor Execution Cycle OPEN stage ● ● ● ● ● PGA memory allocation for cursor processing Parsing of SELECT statement Variable binding SELECT Query execution Move the record pointer to the first record FETCH stage The record, to which the record pointer points, is pulled from the result set. The record pointer moves only in the forward direction. The FETCH phase lives until the last record is reached. CLOSE stage 86 After the last record of the result set is reached, cursor is closed, and allocated memory is flushed off and released back to SGA. Even if an open cursor is not closed, oracle automatically closes it after the execution of its parent block. Syntax and illustration Cursor definition CURSOR [CURSOR NAME] IS [SELECT QUERY] Opening a Cursor OPEN [CURSOR NAME] Fetching records from the cursor FETCH [CURSOR NAME] INTO [LIST OF VARIABLES] Closing a cursor CLOSE [CURSOR NAME] Example Code [4] – The PL/SQL block below declares a cursor, which select employee name, job id and salary for the employees with employee id 100. Note the opening, fetching and closing of the cursor. Here cursor returns a single record. DECLARE CURSOR C_EMP IS SELECT EMPLOYEE_NAME, JOB_ID, SALARY FROM EMPLOYEES WHERE EMPLOYEE_ID=100; L_ENAME VARCHAR2(100); L_JOBID VARCHAR2(10); L_SALARY NUMBER; BEGIN OPEN C_EMP; FETCH C_EMP INTO L_ENAME, L_JOBID, L_SALARY; DBMS_OUTPUT.PUT_LINE(‘Employee ‘||L_ENAME||’ with Job function of ‘||L_JOBID||’ draws ‘||TO_CHAR(L_SALARY)||’ per month’); CLOSE C_EMP; END; 87 RESULT: Thus different cursor programs are executed and verified. EX.NO: 14 TRIGGERS AIM: To write a PL/SQL block to create a trigger for a table while inserting record to a table. DESCRIPTION: A database trigger is a stored procedure that is fired when an insert, update or delete statement is issued against the associated table. Database triggers can be used for the following purposes. ● ● ● ● ● To generate data automatically. To enforce complex integrity. To customize complex security authorizations. To maintain replicate tables. To audit data modifications SYNTAX: Create or replace trigger<trigger_name> [before/after][insert/update/delete] on <table_name> [referencing/{old[as]old/new}] [for each statement /for each row][when<condition>]PL/SQL_block. TYPES OF TRIGGERS: Triggers are categorized into the following types based on when they are fired. 88 ● ● ● ● Before After For each row For each statement(default) PROGRAM 1: create or replace trigger vote_trig after insert on voters_ passed for each row declare v_id number(5); w_id number(5); begin v_id:=: new.voter_id; w_id:=: new.ward_id; delete from voters_master where voter_id=v_id and ward_id=w_id; end; SQL>create table voters_master(voter_id number(5), name varchar2(15), ward_id number(5), dob date, address varchar2(20), primary key(voter_id,ward_id)); Table created. SQL>insert into voters_master value(&voter_id,’&name’,&ward_id,’&dob’,’&address’); rows created. SQL>select * from voters_master; VODER_ID NAME WARD_ID DOB ADDRESS ---------------- ----------------------------- --------------- -----------------22 vivin 77 12-MAR-86 salem-25 110 priya 76 30-JUN-78 salem-24 55 arun 89 05-AUG-62 salem-12 21 saranya 45 17-JUL-87 salem-18 SQL>create table voters_passed(voter_id number(5), ward_id number(5), primary key(voter_id,ward_id)); Table created. SQL>select * from voters_passed; no rows selected OUTPUT: Trigger created. SQL>insert into voters_passed values (21,45); 1 row created. SQL>select* from voters_master; VODER_ID NAME WARD_ID DOB ADDRESS ---------------- --------------------------- --------------------22 vivin 77 12-MAR-86 salem-25 110 priya 76 30-JUN-78 salem-24 89 55 arun 89 05-AUG-62 salem-12 SQL>select * from voters_pased; Voter_id ward_id ---------------------21 45 PROGRAM 2: SQL>create table phone25(cno number(10),cname varchar2(10),salary number(10)); Table created. SQL>desc phone25; Name Null Type ------------------------------ -------- --------------------------------------------------------------------CNO NUMBER(10) CNAME VARCHAR2(10) SALARY NUMBER(10) SQL>insert into phone25 values(&cno,'&cname',&salary); row created. SQL>select * from phone25; CNO CNAME SALARY --------------------- ---------- ---------------------1 ram 12000 2 seeta 17000 3 lakshman 43000 SQL>create or replace trigger salr_trig after insert or delete or update on phone25 for each row begin if updating then dbms_output.put_line('Table is updated'); else if inserting then dbms_output.put_line('Table is inserted'); else if deleting then dbms_output.put_line('Table is deleted'); end if; end if; end if; end; Output: trigger salr_trig Compiled. SQL>update phone25 set salary=90000 where cname='seeta'; 90 1 rows updated. Table is updated. SQL>insert into phone25 values (5,'gita',45000); 1 rows inserted Table is inserted SQL>delete from phone25 where cname='ram'; 1 rows deleted. Table is deleted. PROGRAM 3: SQL>create table mark00(rno number(5),mark number(5),primary key(rno,mark)); create table succeeded. SQL>desc mark00; Name Null Type --------------------- ------------- ------------------RNO NOT NULL NUMBER(5) MARK NOT NULL NUMBER(5) SQL>create table mark01(rno number(5),sname varchar2(10),mark number(5),primary key(rno,mark)); create table succeeded. SQL>desc mark01; Name Null Type -------------------- ----------------- ------------------------RNO NOT NULL NUMBER(5) SNAME VARCHAR2(10) MARK NOT NULL NUMBER(5) SQL>insert into mark01 values (&rno,'&sname',&mark); row created. SQL>select * from mark01; RNO SNAME MARK ---------------- ------------------ ------------1 ram 500 2 seeta 780 3 hanuman 600 SQL>create or replace trigger m9 after insert on mark00 for each row declare r_no number(5); m number(5); 91 begin r_no:=:new.rno; m:=:new.mark; delete from mark01 where rno=r_no and mark=m; dbms_output.put_line('row deleted'); end; Output: M9 Compiled. SQL>insert into mark00 values(2,780); 1 rows inserted dbms output: set serveroutput on row deleted SQL>select * from mark01; RNO SNAME MARK ------------ -------------- --------------1 ram 500 3 hanuman 600 SQL>select * from mark00; RNO MARK ------------- -----------------2 780 RESULT: The PL/SQL block for creating the triggers was executed and the output was verified. 92 EX.NO: 15 Mini Project Banking Enterprise Design Window 93 Adding Library Project = > References => Microsoft ActiveX Data Objects 2.0 Library Coding Dim Con As New ADODB.Connection Dim Rs As New ADODB.Recordset Private Sub CmdAddNew_Click() Rs.AddNew txtClear Text1.SetFocus End Sub Private Sub CmdDelete_Click() On Error Resume Next If Rs.EOF Then 94 MsgBox "No Records" Else Rs.Delete Rs.MoveNext DisplayText MsgBox "Record Deleted" End If End Sub Private Sub CmdFirst_Click() Rs.MoveFirst DisplayText End Sub Private Sub CmdNext_Click() Rs.MoveNext If Not Rs.EOF Then DisplayText Else MsgBox "End Of The Record" Rs.MovePrevious End If End Sub Private Sub CmdUpdate_Click() Rs(0).Value = Val(Text1.Text) Rs(1).Value = Text2.Text Rs(2).Value = Text3.Text Rs(3).Value = Val(Text4.Text) Rs.Update MsgBox "Record Updated" End Sub Private Sub Form_Load() Con.Open "Provider=MSDAORA.1;User ID=cse101;Password=cse101;Data Source=ibmrec;Persist Security Info=False" Con.CursorLocation = adUseClient Rs.Open "select * from Bank", Con, adOpenKeyset, adLockOptimistic End Sub Sub txtClear() 95 Text1.Text = "" Text2.Text = "" Text3.Text = "" Text4.Text = "" End Sub Sub DisplayText() Text1.Text = Rs(0).Value Text2.Text = Rs(1).Value Text3.Text = Rs(2).Value Text4.Text = Rs(3).Value End Sub Private Sub CmdTransact_Click() Form2.Show End Sub Transaction Window Design Coding Dim Con As New ADODB.Connection Dim Rs As New ADODB.Recordset Private Sub CmdDeposit_Click() Dim AccNo As Integer AccNo = Val(Text1.Text) Rs.MoveFirst 96 Do While Not Rs.EOF If Rs(0).Value = AccNo Then Rs(3).Value = Rs(3).Value + Val(Text2.Text) Rs.Update MsgBox "Amount Deposited" End If Rs.MoveNext Loop End Sub Private Sub CmdWithdraw_Click() Dim AccNo As Integer, Bal As Double Rs.MoveFirst AccNo = Val(Text1.Text) Do While Not Rs.EOF If Rs(0).Value = AccNo Then Bal = Rs(3).Value - Val(Text2.Text) If Bal >= 500 Then Rs(3).Value = Rs(3).Value - Val(Text2.Text) Rs.Update MsgBox "Amount Withdrew" Else MsgBox "Balance Problem" End If End If Rs.MoveNext Loop End Sub Private Sub Form_Load() Con.Open "Provider=MSDAORA.1;User ID=cse101;Password=cse101;Data Source=ibmrec;Persist Security Info=False" Con.CursorLocation = adUseClient Rs.Open "select * from Bank", Con, adOpenKeyset, adLockOptimistic End Sub Exercises: 1) Hospital Management System. 2) Railway Reservation System. 3) Personal Information System. 4) Web Based User Identification System. 5) Timetable Management System. 97 6) Hotel Management System 7) Banking system 8) Library management system. 9) Blood bank system 10) Insurance system. 98