Lab Manual 13

Embed Size (px)

Citation preview

  • 8/10/2019 Lab Manual 13

    1/61

    DBMS LAB MANUAL

    II B.Tech(IT) / IV SEMESTER

    Prepared by,

    J.SUBA.,M.E.

    M.A.M COLLEGE OF ENGINEERING AND

    TECHNOLOGY

    SIRUGANUR, TRICHY

  • 8/10/2019 Lab Manual 13

    2/61

    Curriculam & Syllabus (Semester IV)

    S.No. Subject Code Subject

    Theory

    1 MA1252 Probability and Queueing Theory

    2 CS1254 Database Management Systems

    3 EC1257 Microprocessors and Microcontrollers

    4 CS1252 Computer Organization and Architecture

    5 CS1253 Operating Systems

    6 IT1251 Software Engineering and Quality Assurance

    Practical

    7 CS1256 Database Management Systems Laboratory

    8 CS1255 Operating Systems Laboratory

    9 EC1258 Microprocessors Laboratory

    CS1256 DATABASE MANAGEMENT SYSTEMS LABORATORY

    LIST OF EXPERIMENTS

    1. Data Definition, Table Creation, Constraints,

    2. Insert, Select Commands, Update and Delete Commands.

    3. Nested Queries and Join Queries

    4. Views

    5. High level programming language extensions (Control structures, Proceduresand Functions).

    6. Front end tools

    7. Forms

    8. Triggers

    9. Menu Design

    10. Reports.

    11.. Database Design and implementation (Mini Project).

  • 8/10/2019 Lab Manual 13

    3/61

    INDEX

    S.NO LIST OF EXPERIMENTS PAGE NO

    1DATA DEFINITION LANGUAGE,TABLE CREATION,

    CONSTRAINTS

    2DATA MANIPULATION AND DATA CONTROL LANGUAGE

    (INSERT,SELECT,UPDATE AND DELETE)

    3 NESTED QUERIES AND JOINS

    4 VIEWS

    5 CONTROLSTRUCTURES,FUNCTIONAND

    PROCEDURE

    6 FRONT END TOOLS

    7 FORMS

    8 TRIGGERS

    9 MENU DESIGN

    10 REPORTS

    VIVAVOCEQUESTIONSANDANSWERS

  • 8/10/2019 Lab Manual 13

    4/61

    Ex No 1 DATA DEFINITION LANGUAGE, TABLE CREATION, CONSTRAINTS

    AIM:

    To execute the Data Definition Language (DDL) commands and creating the table with constraintsusing RDBMS.

    Data Definition Language

    DDL(Data Definition Language) statements are used to create, delete, or change the objects of a database.Typically a database administrator is responsible for using DDL statements or production databases in alarge database system. The commands used are:

    Create - It is used to create a table. Alter - This command is used to add a new column, modify the existing column definition and to

    include or drop integrity constraint. Drop - It will delete the table structure provided the table should be empty. Truncate - If there is no further use of records stored in a table and the structure has to be retained,

    then the records alone can be deleted. Desc - This is used to view the structure of the table.

    Table Creation

    Rules: Reserved words cannot be used.

    Underscore, numerals, letters are allowed but not blank space. Maximum length for the table name is 30 characters. 2 different tables should not have same name. We should specify a unique column name. We should specify proper data type along with width. We can include not null condition when needed. By default it is null.

    Syntax

    create table {

    fieldname-1 datatype constraints if any,

    fieldname-2 datatype constraints if any,.fieldname-n datatype constraints if any,

    };create table as(select(att-list) from );

    ALTER TABLE - syntax

    alter table add/modify

    (fieldname-1 datatype,fieldname-2 datatype,..fieldname-n datatype

    );

    alter table drop column column name;

    Tab l e a l t er ed.

    DESCRIBING TABLEDesc ;

  • 8/10/2019 Lab Manual 13

    5/61

    CHANGING NAME OF AN OBJECT

    To change the name of a table, view, sequence, or synonym, execute the rename statement.Syntax:rename old name to new name;

    TRUNCATE: - The truncate table statement

    Removes all rows from a table Release the storage space used by that table

    We cannot rollback row removal when using truncate.Syntax:truncate table ;

    DROP TABLE

    1. All data and structure in the table is deleted2. Any pending transactions are committed.3. All indexes are dropped.4. We can not rollback the drop table statement.

    Syntax:drop table ;

    Ta bl e d r o pp ed .

    SET UNUSED OPTION:

    Used to mark one or more columns as unused.

    alter table table name set unused(column name )(or)

    alter table table name set ununsed column column name

    REFERENCING ANOTHER USER TABLE

    Table belonging to other users are not in the users schema, we should use the owners name as

    prefix to those tables.

    Select * from user name .table name

    QUERYING THE DATA DICTIONARY

    To see the names of tables owned by the userSelect table_name from user_tables;

    To view distinct object types owned by the userSelect Distinct object_type from user_objects;

    To view tables, views, synonyms and sequences owned by the user;

    Select * from user_catalog;Constraints:

    The three types of constraints are Domain Integrity Constraints, Entity Integrity Constraints, and

    Referential Integrity Constraints

    Integrity Constraints are used to enforce rules that the columns in a table have to conform with. It is a

    mechanism used by Oracle to prevent invalid data entry into the table.

    1. Domain Integrity Constraintsa. Not Null Constraint The enforcement of Not Null Constraints in a table ensures that the

    table contain values.

    b. Check Constraint Allow only a particular range of values

  • 8/10/2019 Lab Manual 13

    6/61

    2. Entity Integrity Constraintsa. Unique Constraints The unique constraint designates a Column or a group of columns as

    unique key. This allows only unique value to be stored in the column. Rejects duplication.b. Primary Key Constraints Primary key similar to unique key. avoids duplication , relation

    between two tables , does not allow not null values.

    3. Referential Integrity ConstraintsEnforces relationship between tables. It designates a column or group of columns as a foreign key

    Sample Output CONSTRAINTS

    NOT NULL, UNIQUE AND CHECK CONSTRINTS

    SQL> create table vendor_master(vencode varchar(5) unique,venname varchar(7) not null);

    Table created.

    SQL> desc vendor_master;

    Name Null? Type----------------------------------------- -------- ---------VENCODE VARCHAR2(5)VENNAME NOT NULL VARCHAR2(7)

    SQL> alter table vendor_master add(productprice number(10)check(productprice insert into vendor_master values('v001','Sony TV',9100);

    1 row created.

    UNIQUE CONSTRAINT VIOLATION

    SQL> insert into vendor_master values('&vencode','&venname',&productprice);Enter value for vencode: v001Enter value for venname: PhilipsEnter value for productprice: 6000old 1: insert into vendor_master values('&vencode','&venname',

    &productprice)new 1: insert into vendor_master values('v001','Philips',6000)insert into vendor_master values('v001','Philips',6000)*ERROR at line 1:ORA-00001: unique constraint (USER06.SYS_C002807) violatedSQL> edWrote file afiedt.buf1* insert into vendor_master values('&vencode','&venname',

    &productprice)SQL> /Enter value for vencode: v002Enter value for venname: Sony TV

  • 8/10/2019 Lab Manual 13

    7/61

    Enter value for productprice: 6000old 1: insert into vendor_master values('&vencode','&venname',&productprice)new 1: insert into vendor_master values('v002','Sony TV',6000)

    1 row created.

    NULL CONSTRAINT VIOLATION

    SQL> /Enter value for vencode: v003Enter value for venname:Enter value for productprice: 9000old 1: insert into vendor_master values('&vencode','&venname',&productprice)new 1: insert into vendor_master values('v003','',9000)insert into vendor_master values('v003','',9000)*ERROR at line 1:ORA-01400: cannot insert NULL into ("USER06"."VENDOR_MASTER".

    "VENNAME")

    SQL> /Enter value for vencode: v003Enter value for venname: PhilipsEnter value for productprice: 8000old 1: insert into vendor_master values('&vencode','&venname',&productprice)new 1: insert into vendor_master values('v003','Philips',8000)

    1 row created.

    CHECK CONSTRAINT VIOLATION

    SQL> /Enter value for vencode: v004Enter value for venname: AkaiEnter value for productprice: 12000old 1: insert into vendor_master values('&vencode','&venname',&productprice)new 1: insert into vendor_master values('v004','Akai',12000)insert into vendor_master values('v004','Akai',12000)

    *ERROR at line 1:ORA-02290: check constraint (USER06.SYS_C002809) violated

    SQL> /Enter value for vencode: v005Enter value for venname: AiwaEnter value for productprice: 8500old 1: insert into vendor_master values('&vencode','&venname',&productprice)new 1: insert into vendor_master values('v005','Aiwa',8500)1 row created.PRIMARY AND FOREIGN KEY CONSTRAINTS

  • 8/10/2019 Lab Manual 13

    8/61

    SQL> create table order_master(orderno varchar(5) constraint order_primprimary key,odate date,

    vencode varchar(5),o_status char(1) not null,deldate date);

    Table created.

    SQL> desc order_master;Name Null? Type

    ----------------------------------------- -------- ------------------ORDERNO NOT NULL VARCHAR2(5)ODATE DATEVENCODE VARCHAR2(5)

    O_STATUS NOT NULL CHAR(1)DELDATE DATE

    SQL> create table order_detail(orderno varchar2(5) ,itemcode varchar(3),qtyorder number(3),foreign key(orderno) references order_master on delete cascade onupdate cascade);

    Table created.

    SQL> desc order_detail;Name Null? Type----------------------------------------- -------- -----------------ORDERNO VARCHAR2(5)ITEMCODE VARCHAR2(3)QTYORDER NUMBER(3)

    SQL> insert into order_master values('&oredrno','&odate','&vencode',

    '&o_status','&deldate');Enter value for oredrno: o001Enter value for odate: 12-aug-2009Enter value for vencode: v001Enter value for o_status: pEnter value for deldate: 12-sep-2009old 1: insert into order_master values('&oredrno','&odate','&vencode','&o_status','&deldate')new 1: insert into order_master values('o001','12-aug-2009','v001','p','12-sep-2009')

    1 row created.

    PRIMARY KEY CONSTRAINT VIOLATION

    SQL> /Enter value for oredrno: o001Enter value for odate: 11-nov-2008Enter value for vencode: v002Enter value for o_status: pEnter value for deldate: 14-feb-2010old 1: insert into order_master values('&oredrno','&odate','&vencode','&o_status','&deldate')new 1: insert into order_master values('o001','11-nov-2008','v002','p',

  • 8/10/2019 Lab Manual 13

    9/61

    '14-feb-2010')insert into order_master values('o001','11-nov-2008','v002','p','14-feb-2010')*ERROR at line 1:ORA-00001: unique constraint (USER06.ORDER_PRIM) violatedSQL> /Enter value for oredrno: o002Enter value for odate: 13-jan-2007

    Enter value for vencode: v002Enter value for o_status: pEnter value for deldate: 16-oct-2009old 1: insert into order_master values('&oredrno','&odate','&vencode','&o_status','&deldate')new 1: insert into order_master values('o002','13-jan-2007','v002','p','16-oct-2009')

    1 row created.

    SQL> select * from order_master;

    ORDER ODATE VENCO O DELDATE----- --------- ----- - ---------o001 11-NOV-08 voo2 p 14-FEB-10o002 13-JAN-07 v002 p 16-OCT-09

    FOREIGN KEY CONSTRAINT VIOLATION

    SQL> insert into order_detail values('&orderno','&itemcode',&qtyorder);Enter value for orderno: o003

    Enter value for itemcode: i01Enter value for qtyorder: 25old 1: insert into order_detail values('&orderno','&itemcode',&qtyorder)new 1: insert into order_detail values('o003','i01',25)insert into order_detail values('o003','i01',25)*ERROR at line 1:ORA-02291: integrity constraint (USER06.SYS_C002814) violated - parent keynotfound

    SQL> /Enter value for orderno: o001Enter value for itemcode: i01Enter value for qtyorder: 25old 1: insert into order_detail values('&orderno','&itemcode',&qtyorder)new 1: insert into order_detail values('o001','i01',25)

    1 row created.

    SQL> select * from order_detail;

    ORDER ITE QTYORDER----- --- ----------

  • 8/10/2019 Lab Manual 13

    10/61

    o001 i01 25

    SQL>delete from order_master where orderno='o001'*ERROR at line 1:ORA-02292: integrity constraint (USER06.SYS_C002814) violated - childrecord found

    USING on delete cascade with foreign key constraint

    SQL> drop table order_master;

    Table dropped.

    SQL> drop table order_detail;

    Table dropped.

    SQL> create table order_master(orderno varchar(5) constraint order_primprimary key, odate date,

    vencode varchar(5),o_status char(1) not null,deldate date);

    SQL>create table order_detail(orderno varchar2(5) ,itemcode varchar(3),qtyorder number(3),foreign key(orderno) references order_master on delete cascade);

    Table created.

    SQL> insert into order_master values('&oredrno','&odate','&vencode','&o_status','&deldate');

    Enter value for oredrno: o001Enter value for odate: 12-jan-2007Enter value for vencode: voo1Enter value for o_status: pEnter value for deldate: 13-jun-2008old 1: insert into order_master values('&oredrno','&odate','&vencode','&o_status','&deldate')new 1: insert into order_master values('o001','12-jan-2007','voo1','p','13-jun-2008')

    1 row created.

    SQL> /Enter value for oredrno: o002Enter value for odate: 24-sep-2008Enter value for vencode: voo2Enter value for o_status: pEnter value for deldate: 16-jan-2010old 1: insert into order_master values('&oredrno','&odate','&vencode','&o_status','&deldate')new 1: insert into order_master values('o002','24-sep-2008','voo2','p','16-jan-2010')

    1 row created.

  • 8/10/2019 Lab Manual 13

    11/61

    SQL> select * from order_master;

    ORDER ODATE VENCO O DELDATE----- --------- ----- - ---------o001 12-JAN-07 voo1 p 13-JUN-08o002 24-SEP-08 voo2 p 16-JAN-10

    SQL> insert into order_detail values('&orderno','&itemcode',&qtyorder);

    Enter value for orderno: o001Enter value for itemcode: i01Enter value for qtyorder: 25old 1: insert into order_detail values('&orderno','&itemcode',&qtyorder)new 1: insert into order_detail values('o001','i01',25)1 row created.SQL> /Enter value for orderno: o002Enter value for itemcode: i02Enter value for qtyorder: 50old 1: insert into order_detail values('&orderno','&itemcode',&qtyorder)

    new 1: insert into order_detail values('o002','i02',50)1 row created.SQL> select * from order_detail;ORDER ITE QTYORDER----- --- ----------o001 i01 25o002 i02 50

    SQL> delete from order_master where orderno='o001';

    1 row deleted.

    SQL> select * from order_master;

    ORDER ODATE VENCO O DELDATE----- --------- ----- - ---------o002 24-SEP-08 voo2 p 16-JAN-10

    SQL> select * from order_detail;

    ORDER ITE QTYORDER----- --- ----------

    o002 i02 50

    [Note: Deletion of a row in parent is reflected in child table also. ]

    RESULT:

    Thus the Data Definition Language (DDL) and Data Control Language (DCL) commands inRDBMS were executed and verified.

  • 8/10/2019 Lab Manual 13

    12/61

    EX.NO:2 DATA MANIPULATION AND DATA CONTROL LANGUAGE

    (Insert, select, update and delete commands)

    AIM:

    To execute the Data Manipulation Language (DML) and Data Control Language (DCL) commands inRDBMS.

    Data Manipulation Language

    DML commands are the most frequently used SQL commands and is used to query and manipulate theexisting database objects. Some of the commands are

    1. Insert2. Select3. Update4. Delete

    Syntax :

    INSERT: This is used to add one or more rows to a table. The values are separated by commas and

    the data types char and date are enclosed in apostrophes. The values must br entered in the same order asthey are defined.

    Inserting a single row into a table:

    insert into values(fieldvalue-1,fieldvalue-2,,fieldvalue-n);

    Inserting more than one record using a single insert command:

    insert into values(&fieldname-1,&fieldname-2,&fieldname-n);

    Skipping the fields while inserting:

    insert into values (list of values);Other way is to give null while passing the values.insert into (select(att_list) from );

    SELECT: - It is used to retrieve information from the table.it is generally refered to as querying the

    table. We can either display all columns in a table or only specify column from the table.

    SELECT(att_list) FROM [WHERE ];

    Retrieval of all columns from a table:

    Select * from tablename; // This query selects all rows from the table.

    Retrieval of specific columns from a table:It retrieves the specified columns from the table.

    Syntax:Select column_name1, ..,column_namen from table name;

    Elimination of duplicates from the select clause: It prevents retriving the duplicated values .Distinct

    keyword is to be used.

    Syntax:Select DISTINCT col1, col2 from table name;

    Select command with where clause: To select specific rows from a table we include where clause in

    the select command. Itcan appear only after the from clause.

  • 8/10/2019 Lab Manual 13

    13/61

    Syntax:Select column_name1, ..,column_namen from table name where condition;

    Select command with order by clause:

    Syntax:Select column_name1, ..,column_namen from table name where condition order

    by colmnname;

    Select command to create a table:

    Syntax:create table tablename as select * from existing_tablename;

    Select command to insert records:Syntax:insert into tablename ( select columns from existing_tablename);

    UPDATE - It is used to alter the column values in a table. A single column may be updated or morethan one column could be updated.

    update set(fieldname-1 = value, fieldname-2 = value,,fieldname-n = value)[WHERE ];

    DELETE - After inserting row in a table we can also delete them if required. The delete commandconsists of a from clause followed by an optional where clause.

    delete from [where ];

    TRANSACTION CONTROL

    The DML language statements Insert, Delete, Update are affected i.e., written in the databaseunless the user specially says so. The command for this is

    SQL> commit;Commit complete.

    This will commit (write to database) the transactions done by the DML.

    After inserting, updating or deleting the transactions the user does not want to commit the changes, then

    the user can rollback the transaction using the command:SQL> rollback;Rollback complete.It will rollback the transaction and will not commit the changes to the database.

    SQL> savepoint s1;

    Savepoint s1 created.

    It will save the transactions under the name s1.

    DATA CONTROL LANGUAGE:

    Data control language provides users with privilege commands.

    GRANT - Used to give privilege to user on object

    Grant privilege on to ;

    e.g) grant write on employee to user01;

    REVOKE - Used to withdraw the privilege that has been granted to the user.

    Revoke privilege on from ;

    e.g) revoke write on employee from user01;

  • 8/10/2019 Lab Manual 13

    14/61

    Sample Output

    INSERT, SELECT, UPDATE AND DELETE COMMANDS

    SQL> create table person(pid int, lastname varchar2(10),firstname varchar(10),address varchar2(20),age number);

    Table created.

    INSERTING A SINGLE ROW INTO A TABLE

    SQL> insert into person values(1,'Prettina','Anne','Bangalore',14);

    1 row created.

    SQL> insert into person values(2,'Benitto','Anish','Trichy',24);

    1 row created.

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE---------- ---------- ---------- -------------------- ----------1 Prettina Anne Bangalore 142 Benitto Anish Trichy 24

    INSERTING MORE THAN ONE ROW USING A SINGLE INSERT COMMAND

    SQL> insert into person values(&pid,'&lastname','&firstname','&address',&age);Enter value for pid: 3Enter value for lastname: RajEnter value for firstname: Anita

    Enter value for address: ChennaiEnter value for age: 27old 1: insert into person values(&pid,'&lastname','&firstname','&address',&age)new 1: insert into person values(3,'Raj','Anita','Chennai',27)

    1 row created.

    SQL> /Enter value for pid: 4Enter value for lastname: kumarEnter value for firstname: Ashok

    Enter value for address: CoimbatoreEnter value for age: 30old 1: insert into person values(&pid,'&lastname','&firstname','&address',&age)new 1: insert into person values(4,'kumar','Ashok','Coimbatore',30)

    1 row created.

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE---------- ---------- ---------- -------------------- ----------

    1 Prettina Anne Bangalore 142 Benitto Anish Trichy 24

  • 8/10/2019 Lab Manual 13

    15/61

    3 Raj Anita Chennai 274 kumar Ashok Coimbatore 30

    SKIPPING THE FIELDS WHILE INSERTING

    SQL> insert into person(pid,lastname,firstname) values(5,Hinn,Benny);insert into person(pid,lastname,firstname) values(5,'Hinn','Benny')

    1 row created.

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE---------- ---------- ---------- -------------------- ----------

    1 Prettina Anne Bangalore 142 Benitto Anish Trichy 243 Raj Anita Chennai 274 kumar Ashok Coimbatore 305 Hinn Benny

    INSERT VALUES USING MEANINGFUL FIELD NAMES

    SQL> insert into person values(&personid,'&lastname','&firstname','&personaddress',&age);Enter value for personid: 6Enter value for lastname: PrakashEnter value for firstname: BhaskarEnter value for personaddress: AndhraEnter value for age: 40old 1: insert into person values(&personid,'&lastname','&firstname','&personaddress',&age)new 1: insert into person values(6,'Prakash','Bhaskar','Andhra',40)

    1 row created.

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE---------- ---------- ---------- -------------------- ----------

    1 Prettina Anne Bangalore 142 Benitto Anish Trichy 243 Raj Anita Chennai 274 kumar Ashok Coimbatore 305 Hinn Benny

    6 Prakash Bhaskar Andhra 40

    6 rows selected.

    UPDATE VALUES USING CONDITION

    SQL> update person set address='United States'where pid=5;

    1 row updated.

    UPDATE VALUES USING &

    SQL> update person set address ='&address',age=&age where pid=&pid;

  • 8/10/2019 Lab Manual 13

    16/61

    Enter value for address: AssamEnter value for age: 40Enter value for pid: 6old 1: update person set address ='&address',age=&age where pid=&pidnew 1: update person set address ='Assam',age=40 where pid=6

    1 row updated.

    SQL> /

    Enter value for address: BritainEnter value for age: 55Enter value for pid: 5old 1: update person set address ='&address',age=&age where pid=&pidnew 1: update person set address ='Britain',age=55 where pid=5

    1 row updated.

    SELECT COMMAND TO RETRIEVE THE ENTIRE INFORMATION FROM THE TABLE

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE---------- ---------- ---------- -------------------- ----------

    1 Prettina Anne Bangalore 142 Benitto Anish Trichy 243 Raj Anita Chennai 274 kumar Ashok Coimbatore 305 Hinn Benny Britain 556 Prakash Bhaskar Assam 40

    6 rows selected.

    SELECT COMMAND USING 'WHERE' CLAUSE

    SQL>select * from person where lastname= 'Kumar' and address='Coimbatore';

    PID LASTNAME FIRSTNAME ADDRESS AGE---------- ---------- ---------- -------------------- ----------

    4 Kumar Ashok Coimbatore 307 Kumar Chander Coimbatore 45

    SELECT COMMAND TO RETRIEVE THE TOP VALUES

    SQL> select * from person where rownum select * from person where address like 'C%';

  • 8/10/2019 Lab Manual 13

    17/61

    PID LASTNAME FIRSTNAME ADDRESS AGE

    ---------- ---------- ---------- -------------------- ----------3 Raj Anita Chennai 274 kumar Ashok Coimbatore 30

    SQL> select * from person where address like '%i%';

    PID LASTNAME FIRSTNAME ADDRESS AGE

    ---------- ---------- ---------- -------------------- ----------2 Benitto Anish richy 243 Raj Anita Chennai 274 Kumar Ashok Coimbatore 305 Hinn Benny Britain 55

    SELECT COMMAND USING IN OPERATOR

    SQL> select * from person where lastname in('Prettina');

    PID LASTNAME FIRSTNAME ADDRESS AGE

    ---------- ---------- ---------- -------------------- ----------1 Prettina Anne Bangalore 14

    SELECT COMMAND USING BETWEEN OPERATOR

    SQL> insert into person values(7,'Kumar','Chander','Coimbatore',45);

    1 row created.

    SQL> select * from person where lastname between 'Kumar' and 'Kumar';

    PID LASTNAME FIRSTNAME ADDRESS AGE--------- ---------- ---------- -------------------- ----------6 Kumar Ashok Coimbatore 307 Kumar Chander Coimbatore 45

    SELECT COMMAND TO ELIMINATE DUPLICATES

    SQL> select DISTINCT lastname from person;

    LASTNAME----------

    BenittoHinnKumarPrakashPrettinaRaj6 rows selected.

    SELECT COMMAND WITH ORDER BY CLAUSE

    SQL> select pid, firstname,age from person order by age;

  • 8/10/2019 Lab Manual 13

    18/61

    PID FIRSTNAME AGE

    ---------- ---------- ----------1 Anne 142 Anish 243 Anita 274 Ashok 306 Bhaskar 407 Chander 45

    5 Benny 55

    7 rows selected.

    SELECT COMMAND TO CREATE A TABLE

    SQL> create table individual as select * from person;

    Table created.

    SQL> select * from individual;

    PID LASTNAME FIRSTNAME ADDRESS AGE---------- ---------- ---------- ------------ --------

    1 Prettina Anne Bangalore 142 Benitto Anish Trichy 243 Raj Anita Chennai 274 Kumar Ashok Coimbatore 305 Hinn Benny Britain 556 Prakash Bhaskar Assam 407 Kumar Chander Coimbatore 45

    7 rows selected.

    SELECT COMMAND TO INSERT RECORDS

    SQL> insert into individual(select * from person);

    7 rows created.

    SELECT COMMAND WITH FUNCTIONS

    SQL> select count(*) as pid from person;

    PID----------

    7SQL> select count(distinct lastname) as pid from person;

    PID----------

    6SQL> select max(age) from person;

    MAX(AGE)----------

  • 8/10/2019 Lab Manual 13

    19/61

    55

    SQL> select min(age) from person;

    MIN(AGE)----------

    14

    SQL> select sum(age) from person;

    SUM(AGE)----------

    235

    DATA CONTROL LANGUAGE (DCL) COMMANDS

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE------- ---------- ---------- ------------ --------

    1 Prettina Anne BAngalore 142 Benitto Anish Trichy 243 Raj Anita Chennai 274 Kumar Ashok Coimbatore 305 Hinn Benny Britain 556 Prakash Bhaskar Assam 407 Kumar Chander Coimbatore 45

    7 rows selected.

    SQL> commit;

    Commit complete.

    DELETE COMMAND

    SQL> delete from person where lastname='Kumar';

    2 rows deleted.

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE------ ---------- ---------- ------------ --------1 Prettina Anne BAngalore 142 Benitto Anish Trichy 243 Raj Anita Chennai 275 Hinn Benny Britain 556 Prakash Bhaskar Assam 40

    SQL> rollback;

    Rollback complete.

  • 8/10/2019 Lab Manual 13

    20/61

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE------- ---------- ---------- ------------ -------

    1 Prettina Anne BAngalore 142 Benitto Anish Trichy 243 Raj Anita Chennai 274 Kumar Ashok Coimbatore 305 Hinn Benny Britain 55

    6 Prakash Bhaskar Assam 407 Kumar Chander Coimbatore 45

    7 rows selected.

    SQL> savepoint s1;

    Savepoint created.

    SQL> delete from person;

    7 rows deleted.

    SQL> select * from person;

    no rows selected

    SQL> rollback to savepoint s1;

    Rollback complete.

    SQL> select * from person;

    PID LASTNAME FIRSTNAME ADDRESS AGE------ ---------- ---------- ------------- -------

    1 Prettina Anne BAngalore 142 Benitto Anish Trichy 243 Raj Anita Chennai 274 Kumar Ashok Coimbatore 305 Hinn Benny Britain 556 Prakash Bhaskar Assam 407 Kumar Chander Coimbatore 45

    7 rows selected.

    RESULT:

    Thus the Data Manipulation Language (DML) and Data Control Language (DCL) commands inRDBMS were executed and verified.

  • 8/10/2019 Lab Manual 13

    21/61

    EX.NO:3 NESTED QUERIES AND JOINS

    AIM:To execute nested queries and join commands in SQL.

    NESTED QUERIES :

    A subquery is a query within a query. In Oracle, you can create subqueries within your SQL statements.These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.

    JOINS:Join is a query in which data is returned from two or more tables.

    How the join will be performed:

    Step 1: Make the Cartesian product of the given tables.Step 2: Check for the equality on common attributes for the given tables.

    Natural join:

    It returns the matching rows from the table that are being joined.Syntax:

    >select from TN where TN1.attribute=TN2.attribute.Inner join:

    It returns the matching rows from the table that are being joined.Syntax:

    >select from TN1 innerjoin TN2 on TN1.attribute=TN2.attribute.Left outer join:

    It returns all the rows from the table1 even when they are unmatched.Syntax:

    5. select from TN1 left outer join TN2 on TN1.attribute=TN2.attribute.2. select from TN where TN1.attribute(+)=TN2.attribute.

    Right outer join:

    It returns all the rows from the table2 even when they are unmatched.Syntax:

    4. select from TN1 right outer join TN2 on TN1.attribute=TN2.attribute.2. select from TN where TN1.attribute=(+)TN2.attribute.

    Full join:It is the combination of both left outer and right outer join.

    Syntax:>select from TN1 full join TN2 on TN1.attribute=TN2.attribute.

    Sample Output

    NESTED QUERIES - Table Creation

    SQL> create table emp_det(eno number(3) not null, ename varchar2(25),address varchar2(30),basic_sal number(12,2),job_status varchar2(15),dno number(3));

    Table created.

    SQL> create table pro_det(pno number(3) not null,pname varchar2(30),no_of_staff number(3));

    Table created.

  • 8/10/2019 Lab Manual 13

    22/61

    SQL> create table work_in(pno number(3),eno number(3),pjob char(12));

    Table created.SQL> desc emp_det;Name Null? Type

    ----------------------------------------- -------- ----------------------------ENO NOT NULL NUMBER(3)ENAME VARCHAR2(25)ADDRESS VARCHAR2(30)

    BASIC_SAL NUMBER(12,2)JOB_STATUS VARCHAR2(15)DNO NUMBER(3)

    SQL> desc pro_det;Name Null? Type----------------------------------------- -------- ----------------------------PNO NOT NULL NUMBER(3)PNAME VARCHAR2(30)NO_OF_STAFF NUMBER(3)

    SQL> desc work_in;Name Null? Type----------------------------------------- -------- ----------------------------PNO NUMBER(3)ENO NUMBER(3)PJOB CHAR(12)

    SQL> insert into emp_det values(&eno,'&ename','&address',&basic_sal,'&job_status',&dno);Enter value for eno: 1Enter value for ename: SaravanaKumar

    Enter value for address: GandhiNagarEnter value for basic_sal: 8000Enter value for job_status: ManagerEnter value for dno: 10old 1: insert into emp_det values(&eno,'&ename','&address',&basic_sal,'&job_status',&dno)new 1: insert into emp_det values(1,'SaravanaKumar','GandhiNagar',8000,'Manager',10)

    1 row created.

    SQL> /Enter value for eno: 2Enter value for ename: MahendranEnter value for address: RainbowColonyEnter value for basic_sal: 5000Enter value for job_status: SupervisorEnter value for dno: 10old 1: insert into emp_det values(&eno,'&ename','&address',&basic_sal,'&job_status',&dno)new 1: insert into emp_det values(2,'Mahendran','RainbowColony',5000,'Supervisor',10)

    1 row created.

  • 8/10/2019 Lab Manual 13

    23/61

    SQL> /Enter value for eno: 3Enter value for ename:RajkumarEnter value for address: EastCoastRoadEnter value for basic_sal: 10000Enter value for job_status: ProfessorEnter value for dno: 2old 1: insert into emp_det values(&eno,'&ename','&address',&basic_sal,

    '&job_status',&dno)new 1: insert into emp_det values(3,'RajKumar','EastCoastRoad',10000,'Professor',2)

    1 row created.

    SQL> /Enter value for eno: 4Enter value for ename: ShirleyEnter value for address: KKnagarEnter value for basic_sal: 8000

    Enter value for job_status: AsstManagerEnter value for dno: 3old 1: insert into emp_det values(&eno,'&ename','&address',&basic_sal,'&job_status',&dno)new 1: insert into emp_det values(4,'Shirley','KKnagar',8000,'AsstManager',3)

    1 row created.

    SQL> alter table emp_det modify(ename varchar2(15), address varchar2(15));

    Table altered.

    SQL> select * from emp_det;

    ENO ENAME ADDRESS BASIC_SAL JOB_STATUS DNO---------- --------------- --------------- ---------- --------------- ----------1 SaravanaKumar GandhiNagar 8000 Manager 102 Mahendran RainbowColony 5000 Supervisor 103 RajKumar EastCoastRoad 10000 Professor 2

    4 Shirley KKnagar 8000 AsstManager 3SQL> insert into pro_det values(&pno,'pname',&no_of_staff);

    Enter value for pno: 1Enter value for no_of_staff: 2old 1: insert into pro_det values(&pno,'pname',&no_of_staff)new 1: insert into pro_det values(1,'pname',2)

    1 row created.

    SQL> /Enter value for pno: 2Enter value for no_of_staff: 3old 1: insert into pro_det values(&pno,'pname',&no_of_staff)new 1: insert into pro_det values(2,'pname',3)

  • 8/10/2019 Lab Manual 13

    24/61

    1 row created.

    SQL> /Enter value for pno: 3Enter value for no_of_staff: 1old 1: insert into pro_det values(&pno,'pname',&no_of_staff)new 1: insert into pro_det values(3,'pname',1)

    1 row created.

    SQL> select * from pro_det;

    PNO PNAME NO_OF_STAFF---------- ------------------------------ -----------

    1 pname 22 pname 33 pname 1

    SQL>update pro_det set pname='DBMS' where pno=1;

    1 row updated.SQL> update pro_det set pname='COMPILER' where pno=2;1 row updated.SQL>update pro_det set pname='C' where pno=3;1 row updated.

    SQL> select * from Pro_det;

    PNO PNAME NO_OF_STAFF---------- ------------------------------ -----------

    1 DBMS 2

    2 COMPILER 33 C 1

    SQL> insert into work_in values(&pno,&eno,'&pjob');Enter value for pno: 1Enter value for eno: 1Enter value for pjob: Programmerold 1: insert into work_in values(&pno,&eno,'&pjob')new 1: insert into work_in values(1,1,'Programmer')

    1 row created.

    SQL> /Enter value for pno: 2Enter value for eno: 1Enter value for pjob: Analystold 1: insert into work_in values(&pno,&eno,'&pjob')new 1: insert into work_in values(2,1,'Analyst')

    1 row created.

    SQL> /Enter value for pno: 1Enter value for eno: 2

  • 8/10/2019 Lab Manual 13

    25/61

    Enter value for pjob: Analystold 1: insert into work_in values(&pno,&eno,'&pjob')new 1: insert into work_in values(1,2,'Analyst')

    1 row created.

    SQL> /Enter value for pno: 2Enter value for eno: 2

    Enter value for pjob: Programmerold 1: insert into work_in values(&pno,&eno,'&pjob')new 1: insert into work_in values(2,2,'Programmer')

    1 row created.

    SQL> select * from work_in;

    PNO ENO PJOB-- ---------- ------------

    1 1 Programmer

    2 1 Analyst1 2 Analyst2 2 Programmer

    NESTED QUERIES

    (i) SQL> select ename from emp_det where dno not in(select dno from emp_det where ename ='SaravanaKumar');

    ENAME

    ---------------RajKumarShirley

    (ii)SQL> select ename, dno from emp_det where dno = (select dno from emp_det where ename ='RajKumar');

    ENAME DNO--------------- ----------RajKumar 2

    (iii)SQL> select ename from emp_det where eno in(select eno from work_in where pno = (select pnofrom pro_det where pname = 'DBMS')) order by ename;

    ENAME---------------MahendranSaravanaKumar

    (iv)SQL> select ename, basic_sal from emp_det where dno = 2 and basic_sal>(select max(basic_sal) fromemp_det where dno = 10) order by ename;

    ENAME BASIC_SAL--------------- ----------RajKumar 10000

  • 8/10/2019 Lab Manual 13

    26/61

    (v)SQL> select pno,pname from pro_det where exists(select pno from work_in where work_in.pno =pro_det.pno);

    PNO PNAME------ ------------------------------

    1 DBMS2 COMPILER

    (vi)SQL>select ename, job_status,basic_sal from emp_det where (dno,basic_sal) in (select dno,basic_salfrom emp_det where ename ='RajKumar');

    ENAME JOB_STATUS BASIC_SAL--------------- --------------- ----------RajKumar Professor 10000

    (vii)SQL>select * from emp_det where basic_sal=(select max(basic_sal) from emp_det);

    ENO ENAME ADDRESS BASIC_SAL JOB_STATUS DNO------ --------------- --------------- ---------- --------------- ----------

    3 RajKumar EastCoastRoad 10000 Professor 2

    (viii)SQL>select max(basic_sal) from emp_det where basic_sal< (select max(basic_sal) from emp_det);

    MAX(BASIC_SAL)---------------

    8000

    (ix)SQL> select * from emp_det where basic_sal < (select avg(basic_sal) from emp_det);

    ENO ENAME ADDRESS BASIC_SAL JOB_STATUS DNO

    ---- --------------- --------------- ---------- --------------- ----------2 Mahendran RainbowColony 5000 Supervisor 10

    JOINS

    SQL> create table emp(name varchar2(20),salary number(10));

    Table created.

    SQL> insert into emp values('&name',&salary);Enter value for name: ashu

    Enter value for salary: 10000old 1: insert into emp values('&name',&salary)new 1: insert into emp values('ashu',10000)

    1 row created.

    SQL> /Enter value for name: asmaEnter value for salary: 1200old 1: insert into emp values('&name',&salary)new 1: insert into emp values('asma',1200)

    1 row created.

  • 8/10/2019 Lab Manual 13

    27/61

    SQL> /Enter value for name: asifEnter value for salary: 2000old 1: insert into emp values('&name',&salary)new 1: insert into emp values('asif',2000)

    1 row created.

    SQL> /Enter value for name: arifEnter value for salary: 1000old 1: insert into emp values('&name',&salary)new 1: insert into emp values('arif',1000)

    1 row created.

    SQL> /Enter value for name: niyasEnter value for salary: 3000

    old 1: insert into emp values('&name',&salary)new 1: insert into emp values('niyas',3000)

    1 row created.

    SQL> select * from emp;

    NAME SALARY-------------------- ----------ashu 10000asma 1200

    asif 2000arif 1000niyas 3000

    SQL> create table emp1(name varchar2(20),empid number(10));

    Table created.

    SQL> insert into emp1 values('&name',&empid);Enter value for name: fathiEnter value for empid: 12

    old 1: insert into emp1 values('&name',&empid)new 1: insert into emp1 values('fathi',12)

    1 row created.

    SQL> /Enter value for name: sumiEnter value for empid: 32old 1: insert into emp1 values('&name',&empid)new 1: insert into emp1 values('sumi',32)

    1 row created.

  • 8/10/2019 Lab Manual 13

    28/61

  • 8/10/2019 Lab Manual 13

    29/61

    LEFT OUTER JOIN****************

    SQL>select emp.name,salary from emp left outer join emp1 on emp.name=emp1.nameNAME SALARY-------------------- ----------asma 1200asif 2000

    arif 1000niyas 3000ashu 10000

    RIGHT OUTER JOIN*****************SQL>select emp1.name,empid from emp right outer join emp1 on emp.name=emp1.name

    NAME EMPID-------------------- ----------asma 1200

    sweety 9sumi 32wahab 10fathi 12priya 11

    6 rows selected.

    FULL JOIN***********

    SQL>select emp1.name,emp.name,emp1.empid,salary from emp full join emp1 onemp.name=emp1.name

    NAME NAME EMPID SALARY-------------------- -------------------- ---------- ----------asma asma 1200 1200

    asif 2000arif 1000niyas 3000ashu 10000

    sweety 9sumi 32wahab 10fathi 12priya 11

    10 rows selected.RESULT:

    Thus the nested queries and join operations are executed and verifiedin DBMS.

  • 8/10/2019 Lab Manual 13

    30/61

    EX.NO:4 VIEWS

    AIM:

    To study and create View commands

    VIEWS:

    In SQL, a view is a virtual table based on the result-set of an SQL statement.A view contains rows and

    columns, just like a real table. The fields in a view are fields from one or more real tables in the database.

    SQL CREATE VIEW Statement

    In SQL, a view is a virtual table based on the result-set of an SQL statement.

    A view contains rows and columns, just like a real table. The fields in a view are fields from one or morereal tables in the database.

    SQL CREATE VIEW Syntax

    CREATE VIEW view_name AS

    SELECT column_name(s)FROM table_nameWHERE condition

    SQL Updating a View

    You can update a view by using the following syntax:

    SQL CREATE OR REPLACE VIEW Syntax

    CREATE OR REPLACE VIEW view_name ASSELECT column_name(s)FROM table_name

    WHERE condition

    SQL Dropping a View

    You can delete a view with the DROP VIEW command.

    SQL DROP VIEW Syntax

    DROP VIEW view_name

    Sample Output

    TABLE 1 CREATION

    ***************`SQL> create table aa(name varchar2(20),book number(10),edition number(20),price number(20),

    ISBN number(20));

    Table created.

    SQL> insert into aa values('&name',&number,&edition,&price,&ISBN);Enter value for name: bbEnter value for number: 23Enter value for edition: 2001Enter value for price: 12

    Enter value for isbn: 23435

  • 8/10/2019 Lab Manual 13

    31/61

    old 1: insert into aa values('&name',&number,&edition,&price,&ISBN)new 1: insert into aa values('bb',23,2001,12,23435)

    1 row created.

    SQL> /Enter value for name: ccEnter value for number: 55Enter value for edition: 342

    Enter value for price: 76Enter value for isbn: 687478old 1: insert into aa values('&name',&number,&edition,&price,&ISBN)new 1: insert into aa values('cc',55,342,76,687478)

    1 row created.

    SQL> /Enter value for name: ddEnter value for number: 2Enter value for edition: 1233

    Enter value for price: 123Enter value for isbn: 53616578old 1: insert into aa values('&name',&number,&edition,&price,&ISBN)new 1: insert into aa values('dd',2,1233,123,53616578)

    1 row created.

    SQL> /Enter value for name: eeEnter value for number: 21Enter value for edition: 1111

    Enter value for price: 111Enter value for isbn: 12435798old 1: insert into aa values('&name',&number,&edition,&price,&ISBN)new 1: insert into aa values('ee',21,1111,111,12435798)

    1 row created.

    TABLE 2 CREATION*****************

    SQL> create table qq(name varchar2(20),book number(10),author varchar(20),publisher varchar2(20),ISBN number(20));

    Table created.

    SQL> select * from aa;

    NAME BOOK EDITION PRICE ISBN-------------------- ---------- ---------- ---------- ----------bb 23 2001 12 23435cc 55 342 76 687478dd 2 1233 123 53616578ee 21 1111 111 12435798

  • 8/10/2019 Lab Manual 13

    32/61

    SQL> insert into qq values('&name','&author',&number,'&publisher',&ISBN);Enter value for name: bbEnter value for author: 21Enter value for number: 23Enter value for publisher: dfdEnter value for isbn: 573568old 1: insert into qq values('&name','&author',&number,'&publisher',&ISBN)new 1: insert into qq values('bb','21',23,'dfd',573568)

    1 row created.

    SQL> /Enter value for name: ccEnter value for author: 43Enter value for number: 55Enter value for publisher: fgEnter value for isbn: 65839old 1: insert into qq values('&name','&author',&number,'&publisher',&ISBN)new 1: insert into qq values('cc','43',55,'fg',65839)

    1 row created.

    SQL> /Enter value for name: eeEnter value for author: 44Enter value for number: 21Enter value for publisher: dfdEnter value for isbn: 1235798old 1: insert into qq values('&name','&author',&number,'&publisher',&ISBN)new 1: insert into qq values('ee','44',21,'dfd',1235798)

    1 row created.

    SQL> /Enter value for name: ooEnter value for author: 87Enter value for number: 34Enter value for publisher: gfhEnter value for isbn: 6358379old 1: insert into qq values('&name','&author',&number,'&publisher',&ISBN)new 1: insert into qq values('oo','87',34,'gfh',6358379)

    1 row created.

    SQL> select * from qq;

    NAME BOOK AUTHOR PUBLISHER-------------------- ---------- -------------------- -------------------- ISBN----------bb 21 23 dfd

    573568

    cc 43 55 fg65839

  • 8/10/2019 Lab Manual 13

    33/61

    ee 44 21 dfd

    1235798

    NAME BOOK AUTHOR PUBLISHER ISBN-------------------- ---------- -------------------- -------------------- ----------oo 87 34 gfh 6358379

    CREATE VIEW STATEMENT**********************SQL>create view ww as select book,name,publisher from qq where ISBN=573568

    View created.

    SQL> select * from ww;

    BOOK NAME PUBLISHER- --------- -------------------- --------------------

    21 bb dfd

    UPDATE VIEW STATEMENT**********************

    SQL> update ww set publisher='qwa'where book=21;

    1 row updated.

    SQL> select * from ww;

    BOOK NAME PUBLISHER---------- -------------------- --------------------

    21 bb qwa

    SQL> create view wq as select name,ISBN,publisher from qq where book>21

    View created.

    SQL> select * from wq;

    NAME ISBN PUBLISHER-------------------- ---------- --------------------cc 65839 fgee 1235798 dfdoo 6358379 gfh

    SQL> create view ss as select name,book from aa union select name,book from qq;

    View created.

    SQL> select * from ss;

    NAME BOOK

  • 8/10/2019 Lab Manual 13

    34/61

    -------------------- ----------bb 21bb 23cc 43cc 55dd 2ee 21ee 44oo 87

    8 rows selected.

    COMPLEX VIEW*************

    SQL> create view er as select author,name,ISBN from qq where book>43;

    View created.

    SQL> select * from er;

    AUTHOR NAME ISBN-------------------- -------------------- ----------21 ee 123579834 oo 6358379

    SQL>select name from(select * from qq where publisher='fg')where ISBN=65839;

    NAME--------------------

    Cc

    DROP VIEW*************SQL> drop view er;

    View dropped

    Result

    Thus the view creation commands are executed successfully.

  • 8/10/2019 Lab Manual 13

    35/61

    EX.NO:5 FUNCTIONS AND PROCEDURE

    AIM:

    To write PL/SQL(Functions)and to understand stored procedures in SQL.

    FUNCTION:

    A function is a subprogram that computes a value. The syntax for creating a function is givenbelow

    Create or replace function[argument]Return datatype is

    (local declaration)begin

    (executable statements)[Exception]

    (exception handlers)end

    PROCEDURE:

    CREATE [ORREPLACE] PROCEDURE PROCEDURENAME[PARAMETER[IN/OUT/IN/IN OUT] DATATYPE[:=/DEFAULT EXPRESSION][(PARAMETER)]IS/ASDECLARATIONBEGINPL/SQL CODES

    [EXCEPTION]END

    Sample Output

    *****FUCTION USING FOR STATEMENT*****

    SQL>create or replace function fact(a number)return number as2 i number;3 f number;4 begin

    5 f:=1;6 for i in 1..a7 loop8 f:=f*i;9 end loop;

    10 return f;11* end fact;

    SQL> /

    Function created.

  • 8/10/2019 Lab Manual 13

    36/61

    *********FUNCTION USING WHILE STATEMENT *************

    SQL> create or replace function fact(a number) return number as2 i number;3 f number;4 begin5 f:=1;6 i:=1;7 while (ibegin

    2 dbms_output.put_line('the factorial='||fact(&a));3* end;SQL> /Enter value for a: 4old 2: dbms_output.put_line('the factorial='||fact(&a))new 2: dbms_output.put_line('the factorial='||fact(4));the factorial=24

    PL/SQL procedure successfully completed.

    *****PROCEDURE TO FIND WHETHER A GIVEN NUMBER IS ODD OR EVEN*********

    SQL> declare2 n number;3 begin4 n:=&n;5 if(mod(n,2)=0)then6 dbms_output.put_line(n||'is even');7 else8 dbms_output.put_line(n||'is odd');9 end if;

    10 end;

    11 /

    Enter value for n: 3old 4: n:=&n;new 4: n:=3;3is odd

    PL/SQL procedure successfully completed.

  • 8/10/2019 Lab Manual 13

    37/61

    **********PROCEDURE TO DISPLAY 1-10 USING WHILE*******1 declare2 n number;3 i number;4 begin5 n:=10;6 i:=1;7 while (i /123456

    78910

    PL/SQL procedure successfully completed.***********Procedure to display some numbers lesser than given number**********

    1 declare2 num number;3 i number;4 begin

    5 num:=&num;6 i:=1;7 loop8 dbms_output.put_line(i);9 exit when(i>num);

    10 i:=i+1;11 end loop;12* end;

    SQL> /Enter value for num: 4old 5: num:=&num;

    new 5: num:=4;12345PL/SQL procedure successfully completed.

    RESULT:

    Thus the functions and stored procedures are executed in SQL.

  • 8/10/2019 Lab Manual 13

    38/61

    Ex.no:6 FRONT END TOOLS

    AIM:

    To study about Visual Basic forms and controls

    Visual Basic:Visual Basic is Easy to learn Programming language. With Visual Basic one can develop Windows basedapplications and games.Visual Basic is much more easier to learn than other language (like Visual C++),and yet it's powerful programming language.

    Visual Basic suits more for application developing than for Games developing. We can createsophisticated games using Visual Basic, But to make a really advanced professional game like Quake 2,other language (like C++), can be chosen which are harder to program with. However, Visual Basic willbe probably powerful enough to suit all your application and games programming needs.

    The advantages of Visual Basic:1) It's simple language. Things that may be difficult to program with other language,can be done in VisualBasic very easily.2) Because Visual Basic is so popular, there are many good resources (Books,Web sites, News groups andmore) that can help us learn the language.

    3) There are many tools (Sharewares and Freewares) on the internet that will reduce the programmingtime.

    Creating the Project

    First thing to do is to create a Directory where all VB Projects can be saved. Call it VBApps, forexample. Then start VB. The first screen will ask whether to open a new project or an existing one - it'sobviously a new one and it will be a Standard EXE. Then, maximize all the windows. Now, save theproject. It will first prompt to save the form - call it Score.frm - and then the Project - call it Scorebrd.vbp.From now on, do File-->Save Project very, very frequently.

  • 8/10/2019 Lab Manual 13

    39/61

    Before starting to build-up the form, it will make it easier if the the color of the form is changed. Tochange the color, just click anywhere on the form, go to the properties window, find the property calledBackColor and change it to the standard Window background (teal) or to any color desired in the palette.

    Suppose if we need 6 labelsand 2 command buttonsgo to the Toolbox. Each one of the object that iskept on a Form is called acontrol. To get a control , click on the control, come back to the Form and clickand drag the control to the size and position needed. Position the controls somewhat like in the diagrambelow.

    Now that we have a bunch of controls on the form, we have to jazz them up a bit. We do this by changingthe Propertiesof the controls in the Properties window. Each control has a whole series of properties,

    most of which we won't need right now. The ones we do need are:

  • 8/10/2019 Lab Manual 13

    40/61

    Alignment = how text aligns in the controlBackColor = choose the color of the backgroundCaption = the text that will appear in the control

    Font = choose the font type and sizeForeColor = choose the color of the text (foreground)

    As with all Windows applications, We can select multiple controls with (Ctrl)+(Click) and change aproperty for all of them at once. For example, if all backgrounds are white, select all controls, changeForeColor to white and all of them are modified. Change the form to look like the one below. Note thatyou do not have to change the Caption for Label4, Label5 and Label6 and that you can't change the color

    of the buttons. They insist on being what was called in the old days "IBM grey". Don't forget to save theproject often as you go along!

    If the application is executed at this point, the Form appears, just the way it was created. However if onany of the controls is clicked, absolutely nothing happens!There are eventsthat occur; the form opens, abutton is clicked, etc. But, there is nothing that tells the form what to do when it sees an event. That is whycode, also called script has to be written.

  • 8/10/2019 Lab Manual 13

    41/61

    To switch between the Code window and the Form window, use the buttons just over the Project Explorerwindow (diagram on the left).Once in the Code window, We have the option of seeing all the code for the Project or the code for oneevent at a time. Use the buttons in the lower left-hand corner (diagram on the right).To select the object and the event to code, use the two Listboxes at the top of the Code window. The oneon the left for the object and the one on the right for the event. Start with General ... Declarationsandthen Form ... Load, etc.

    Now we can Runit and see something happen. When the Form loads, it will initialize the fields that wespecified in the code.Now code the Command1 button and Run it to see the result.

    RESULT:

    Thus the Visual Basic forms and controls are studied.

  • 8/10/2019 Lab Manual 13

    42/61

  • 8/10/2019 Lab Manual 13

    43/61

    Form design in Visual Basic (Front end)

  • 8/10/2019 Lab Manual 13

    44/61

  • 8/10/2019 Lab Manual 13

    45/61

  • 8/10/2019 Lab Manual 13

    46/61

    Code for FormDim con As New ADODB.ConnectionDim rs As New ADODB.Recordset

    Private Sub add_Click()rs.AddNewText1.Text = ""Text2.Text = ""Text3.Text = ""Text4.Text = ""Text5.Text = ""Text6.Text = ""Text1.SetFocusEnd Sub

    Private Sub delete_Click()rs.deleteMsgBox "Record deleted"rs.MoveFirstCall displayEnd Sub

    Private Sub exit_Click()rs.Closecon.CloseUnload MeEnd Sub

  • 8/10/2019 Lab Manual 13

    47/61

    Private Sub Form_Load()con.CursorLocation = adUseClientcon.Open "Provider=MSDAORA.1;password=user02;User ID=user02;Data Source=orcl"rs.Open "select * from emp_details", con, adOpenDynamic, adLockOptimisticCall displayEnd SubPrivate Sub display()Text1.Text = rs.Fields("empname")

    Text2.Text = rs.Fields("empno")Text3.Text = rs.Fields("designation")Text4.Text = rs.Fields("dept")Text5.Text = rs.Fields("salary")Text6.Text = rs.Fields("address")End Sub

    Private Sub save_Click()rs(0) = Text1.Textrs(1) = Val(Text2.Text)rs(2) = Text3.Text

    rs(3) = Text4.Textrs(4) = Val(Text5.Text)rs(5) = Text6.TextEnd Sub

    Private Sub update_Click()If rs.EditMode = adEditAdd Thenrs(0) = Text1.Textrs(1) = Val(Text2.Text)rs(2) = Text3.Textrs(3) = Text4.Text

    rs(4) = Val(Text5.Text)rs(5) = Text6.TextEnd Ifrs.updateEnd Sub

    Table Creation in Oracle (Backend)

    SQL> create table emp_details(empname varchar2(20),empno number(10),designation varchar2(15),deptvarchar2(10), salary number, address varchar2(20));

    Table created.

    SQL> insert into emp_details values('&empname',&empno,'&designation','&dept',&salary,'&address');Enter value for empname: subaEnter value for empno: 1234Enter value for designation: APEnter value for dept: ITEnter value for salary: 21047Enter value for address: IBcolonyold 1: insert into emp_details values('&empname',&empno,'&designation','&dept',&salary,'&address')new 1: insert into emp_details values('suba',1234,'AP','IT',21047,'IBcolony')

  • 8/10/2019 Lab Manual 13

    48/61

  • 8/10/2019 Lab Manual 13

    49/61

    EX.NO:8 TRIGGERS

    AIM:

    To perform High-level language extension with triggers (Student mark list).SYNTAX:

    CREATE[OR REPLACE]TRIGGER[schema.]trigger{BEFORE|AFTER|INSTEAD OF}{DELETE|INSERT

    |UPDATE[OF column[,column].....]}|OR {DELETE|INSERT|UPDATE[OF column,[,column]....]}]...ON[schema.]{table|view}REFERENCING(OLD[AS]old|NEW[AS]new...]FOR EACH{ROW|STATEMENT}{WHEN(condition)}]

    DESCRIPTION:

    The details about the students mark are being in the stu table with attributes.Name, Rollno, Mark, Mark2, Mark3.

    The stu1 table consists of attributes, Rollno, Total, Average, ResultThe details of the first table are being given in the prompt by the user. The total, average are processed forcurrently processed row in the stu table using after insert on trigger the values are placed in the table stu1.

    Trigger

    Create or replace trigger strigAfter insert on st1For each rowDeclareTotal number(8);Avg number(8);Result varchar2(20);BeginTotal:=(:new.m1+:new.m2+:new.m3);Avg:=total/3;If(:new.m1>50 and :new.m2>50 and:new.m3>50) yhenResult:=pass;ElseResult:=fail;End if;Insert into st2 values(:new.rollno,total,avg,result);End;/Trigger created

    SQL>insert into st1 values(raja,004,100,99,90)1 row createdSQL>select * from st2;ROLLNO TOTAL AVG RESULT4 289 96 PassRESULT:

    Thus the high-level language extension with triggers has been performed for generating thestudents mark list.

  • 8/10/2019 Lab Manual 13

    50/61

    EX.NO:9 MENU DESIGN

    AIM:

    To design menus using menu editor in Visual Basic.

    PROCEDURE:

    To create the following menus,Color

    o Set c ol or Red Green White

    Size Large Small

    Exit

    It is required to do the following things:

    1. Exit the program if the user clicks Exit menu.

    2. Change the colour of the form if the user clicks a particular colour.

    3. Change the size of the form if the user clicks any of the option in size menu.

    Steps to be followed:

    1. Start a new VB project

    2. Add a MDI form to the project by clicking Add MDI form from Project menu.

    3. Create menus.

    Name this is the name you use to reference the menu control from code.

    Caption this is the text that appears on the control.

    Click OK button, the menus will be created on the top of MDI form.

    4. Either we can use the MDI form to see the changes or a separate form can be added to show

    the changes on clicking the menu items.

    5. Double-click menu item and add codes there.

    6. Choose the startup object as MDIForm1 from the Project->properties menu.

    7. Run the project.

  • 8/10/2019 Lab Manual 13

    51/61

  • 8/10/2019 Lab Manual 13

    52/61

  • 8/10/2019 Lab Manual 13

    53/61

    Code for Menu EditorPrivate sub mnuexit_click()

    Unload Form1

    End Sub

    Private sub mnublue_click()

    Form1.BackColor=vbBlue

    mnured.Enabled=Truemnublue.Enabled=False

    mnuwhite.Enabled=True

    End Sub

    Private sub mnularge_click()

    Form1.WindowState=2

    mnusmall.Enabled= True

    mnularge.Enabled= FalseEnd Sub

    Private sub mnured_click()

    Form1.BackColor=vbRed

    mnured.Enabled= False

    mnublue.Enabled= True

    mnuwhite.Enabled=True

    End Sub

    Private sub mnusmall_click()

    Form1.WindowState=0

    mnusmall.Enabled= False

    mnularge.Enabled= True

    End Sub

    Private sub mnuwhite_click()

    Form1.BackColor=vbWhite

    mnured.Enabled= True

    mnublue.Enabled= True

    mnuwhite.Enabled=False

    End Sub

    RESULT:Thus the menu editor has been created in Visual Basic..

  • 8/10/2019 Lab Manual 13

    54/61

    Ex.No.10 REPORTS

    AIM:

    To generate data report from the existing database.

    OBJECTIVE:

    Once you have gone to all the trouble of developing and managing a database, it is nice to have theability to obtain printed or displayed information from your data. The process of obtaining suchinformation is known as creating a data report.

    There are two steps to creating a data report. First, we need to create a Data Environment. This isdesigned within Visual Basic and is used to tell the data report what is in the database. Second, we createthe Data Report itself. This, too, is done within Visual Basic. The Data Environment and Data Report filesthen become part of the Visual Basic project developed as a database management system.

    The Visual Basic 6.0 data report capabilities are vast and using them is a detailed process. The use ofthese capabilities is best demonstrated by example. We will look at the rudiments of report creation bybuilding a tabular report for our phone database.

    Example - Phone Directory - Building a Data Report

    We will build a data report that lists all the names and phone numbers in our phone database. We will dothis by first creating a Data Environment, then a Data Report. We will then reopen the phone databasemanagement project and add data reporting capabilities.

    Creating a Data Environment

    1. Start a new StandardEXEproject.

    2. On the Project menu, click AddDataEnvironment. If this item is not on the menu, clickComponents. Click the Designerstab, and choose DataEnvironmentand click OKto add the designerto your menu.

    3. We need to point to our database. In the DataEnvironmentwindow, right-click the Connection1taband select Properties and set the connection.

    4. We now tell the Data Environmentwhat is in our database. Right-click the Connection1tab and clickRename. Change the name of the tab to Phone. Right-click this newly named tab and click AddCommand to create a Command1tab. Right-click this tab and choose Properties. Assign the followingproperties:

    Command Name - PhoneListConnection - PhoneDataBase Object - TableObjectName - PhoneList

    5. Click OK. All this was needed just to connect the environment to our database.6. Display the properties window and give the data environment a name property of denPhone. Click Fileand SavedenPhone As. Save the environment in an appropriate folder. We will eventually add this file toour phone database management system.

  • 8/10/2019 Lab Manual 13

    55/61

    Creating a Data Report

    Once the Data Environment has been created, we can create a Data Report. We will drag things out of theData Environment onto a form created for the Data Report, so make sure your Data Environment window

    is still available.

    1. On the Project menu, click Add Data Report and one will be added to your project. If this item is not onthe menu, click Components. Click the Designers tab, and choose Data Report and click OK to add thedesigner to your menu.

    2. Set the following properties for the report:

    Name - rptPhoneCaption - Phone DirectoryDataSource - denPhone (your phone data environment - choose, dont type)DataMember - PhoneList (the table name - choose dont type)

    3. Right-click the Data Reportand click Retrieve Structure. This establishes a report format based onthe Data Environment.

    4. Note there are five sections to the data report: a Report Header, a Page Header, a Detail section, a PageFooter, and a Report Footer. The headers and footers contain information you want printed in the reportand on each page. To place information in one of these regions, right-click the selected region, click AddControl, then choose the control you wish to place. These controls are called data report controls andproperties are established just like you do for usual controls. Try adding some headers.

    5. The Detail section is used to layout the information you want printed for each record in your database.We will place two field listings (Name, Phone) there. Click on the Name tab in the Data Environmentwindow and drag it to the Detail section of the Data Report. Two items should appear: a text box Nameand a text box Name (PhoneList). The first text box is heading information. Move this text box into the

    Page Header section. The second text box is the actual value for Name from the PhoneList table. Line thistext box up under the Name header. Now, drag the Phone tab from the Data Environment to the DataReport. Adjust the text boxes in the same manner. Our data report will have page headers Name andPhone. Under these headers, these fields for each record in our database will be displayed. When done, theform should look something like this:

  • 8/10/2019 Lab Manual 13

    56/61

    In this form, Weve resized the labels a bit and added a Report Header. Also, make sure you close up theDetail section to a single line. Any space left in this section will be inserted after each entry.

    6. Click File and Save rptPhone As. Save the environment in an appropriate folder. We will now reopenour phone database manager and attach this and the data environment to that project and add capabilitiesto display the report.

    Accessing the Data Report

    1. Reopen the phone directory project. Add a command button named cmdReport and give it a Caption of

    Show Report. (There may be two tabs in your toolbox, one named General and one named DataReport.Make sure you select from the General tools.)

    2. We will now add the data environment and data report files to the project. Click the Project menu item,then click Add File. Choose denPhone and click OK. Also add rptPhone. Look at your Project Window.Those files should be listed under Designers.

    3. Use this code in cmdReport_Click:

    Private Sub cmdReport_Click()rptPhone.ShowEnd Sub

    4. This uses the Show method to display the data report.

    5. Save the application and run it. Click the Show Report button and this should appear:

  • 8/10/2019 Lab Manual 13

    57/61

    RESULT:

    Thus the Report has been generated in Visual Basic..

  • 8/10/2019 Lab Manual 13

    58/61

    VIVA VOCE QUESTIONS & ANSWERS

    1. What is a database?A DBMS is a complex software system that is used to manage, store and manipulate data andmetadata used to describe the data.

    2. What is DBMS?It is a collection of programs that enables user to create and maintain a database. In other words itis general-purpose software that provides the users with the processes of defining, constructing andmanipulating the database for various applications.

    3. What is a Database system?The database and DBMS software together is called as Database system.

    4. Advantages of DBMS. Redundancy is controlled. Unauthorised access is restricted.

    Providing multiple user interfaces. Enforcing integrity constraints.

    Providing backup and recovery.5. Disadvantage in File Processing System

    Data redundancy & inconsistency.

    Difficult in accessing data. Data isolation. Data integrity. Concurrent access is not possible. Security Problems.

    6. What is a key? what are different keys in database?A Key is nothing but a attribute or group of attributes. They are used to perform some specificoperation depending on their operation. The keys are classified into primary key, secondary key,alternative key, super key, candidate key, compound or concatenated or composite key.

    7. What is a primary key?

    A primary key is an attribute to identify a record uniquely is considered to be primary key. for egin the student table student_no is the primary key because it can be used to identify unique recordor unique student.

    8. What is a secondary key?An attribute used to identify a group of records satisfying a given condition is said to be a

    secondary key. In the employee table, designation is a secondary key because more than oneemployee can have the same designation.

    9. What is a candidate key?Register no usually allotted in the exams is also unique for each student in that case for identifying

    a student uniquely either student_no or register_no can be used. Here two different candidates are

    contesting for primary key post. Any of them can be selected as primary key.10.What is an alternate key?

    If any one of the candidate keys among the different candidate keys available is selected as

    primary key then remaining keys are called alternate key.11.What is a super key?

    With primary key if any other attribute is added then that combination is called super key. In otherwords, primary key is the minimum possible super key. In the student table student_no +student_name is one of the super key.

    12.What is a composite key?If the primary key is combination of more than one key then it is called the composite key. In the

    table called marks student_no + subject is the composite key.

  • 8/10/2019 Lab Manual 13

    59/61

    13.What is a relation?A Relation consists of a homogeneous set of tuples.

    14.What is a table?it is the representation of a relation having records as rows and attributes as columns.

    15.What is an attribute?An object or entity is characterized by its properties or attributes. In relational database systemsattributes corresponds to fields.

    16.What is a domain?The set of allowable value for the attribute is the domain of the attribute.

    17.What is a tuple?Tuples are the members of a relation. An entity type having attributes can be represented by set ofthese attributes called tuple.

    18.What is a selection?An operation that selects only some of the tuples in the relation is known as selection operation.The selection operation yields a horizontal subset of a given relation.

    19.what is a join operation?The join operation allows the combination of two relations to form a new relation.

    20.What are base operations in relational algebra?Union:- The term of the relation as performed by combining the tuples from one relation with

    those of a second relation to produce a third relation. Duplicate tuples are eliminated. The relationmust be union compatible.Difference:- The difference of two relations is a third relation having tuples that occur in the first

    relation but not in the second relation.Intersection:- The intersection operation selects the common tuples from the two relations.

    cartesian product:- The cartesian product of two relations is the concatenation of tuplesbelonging to the two relations. A new resultant scheme is created consisting of concatenation of all

    possible combination of tuples.21.What are different DBMS facilities? How many types of facilities are provided by a DBMS?

    1)The data definition facility or data definition language(DDL)

    2)The data manipulation facility or data manipulation language(DML)3)The data control facility(DCL)

    22.What is Data Definition Language?Data scheme is specified by a set of definitions which are expressed b a special language called aDDL.

    23.What is Data Dictionary?A Data Dictionary is a file that contains metadata i.e data about data. This file is consulted beforeactual is read or modified in the database system.

    24.What is a DML?A DML is a language that enables users to access or manipulate data as organized by theappropriate data model. There are basically two types:

    1)procedural DML require a user to specify what data is needed and how to get it.2)non procedural DML require a user to specify what data is needed without specifying how to get

    it.25.What is a query?

    A query is a statement requesting the retrieval of information.26.What is a query language?

    The portion of DML that involves information retrieval is called a query language.27.What are the advantages of DBMS?

    Reduction of redundancies, Integrity, Security, Conflict resolution, Data independence, shareddata, Data quality enhanced.

  • 8/10/2019 Lab Manual 13

    60/61

    28.What is a SQL?Structured query language(sql) originated in 1974 at IBM.SQL is the data definition andmanipulation language.

    29.What are the features of SQL?Portability, client server architecture, dynamic data definition, multiple views of data, complete

    data base language, interactive, high level structure and SQL standards.30.How SQL organizes the data?

    SQL organizes data as databases, tables, indexes, views.

    31.What is data definition?

    SQL lets a user to define the data structure and relationship at the stored data.32.What is data retrieval?

    Allows a user or an application program to retrieve the stored data.33.What is data sharing?

    Data can be shared by more than one user.

    34.What is a view?It is an object of SQL. A query can be defined, stored and named. This is called view.

    35.What is normalization?It is a process of analysing the given relation schemas based on their Functional Dependencies(FDs) and primary key to achieve the properties Minimizing redundancy Minimizing insertion, deletion and update anomalies.

    36.What is a first normal form?A relation which contains no multi valued attributes.

    37.What is a second normal form?A relation is in second normal form for if it is first normal form and every non key attribute is fully

    functionally dependent on primary key.38.What is a third normal form?

    A relation is in third normal form if for every functional dependency F :x->y is aDkey.39.What is BCNF?

    Boyce-code normal form.40.What is fifth normal form?

    A relation which eliminates join dependencies.41.What is Functional Dependency?

    A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsetsof R specifies a constraint on the possible tuple that can form a relation state r of R. The constraintis for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means thevalue of X component of a tuple uniquely determines the value of component Y.

    42.What is Lossless join property?It guarantees that the spurious tuple generation does not occur with respect to relation schemas

    after decomposition.43.What are the commands to delete, modify and insert a record in the table?

    DELETE, UPDATE, INSERT INTO.

    44.What is time stamping?In the time stamping based method, a serial order is created among the concurrent transactions byassigning to each transaction a unique non decreasing numbers .you will be allocating fixed timefor each transaction.

    45.What is data base schema?It is the description of the database i.e its data structure and not the detail.

    46.What is a self join?

    Joining the table to the same table.

  • 8/10/2019 Lab Manual 13

    61/61

    47.What are the different aggregate functions in SQL?AVG(), MIN(), MAX(), COUNT(), SUM().

    48.What is data integrity?Data must satisfy the integrity constraints of the system.

    49.What is data independence?Data independence means that the application is independent of the storage structure and accessstrategy of data. In other words, The ability to modify the schema definition in one level should

    not affect the schema definition in the next higher level.

    Two types of Data Independence: Physical Data Independence: Modification in physical level should not affect the logical level. Logical Data Independence: Modification in logical level should affect the view level.NOTE: Logical Data Independence is more difficult to achieve

    50.What is dead locking?It is the situation where two transactions are waiting for other to release a lock on an item.

    51.What is decryption?Taking encoded text and converting it into text that you are able to read.

    52.What is a distributed database?A Database in which the datails contained within a number of separate subsystems usually indifferent locations.

    53.What is an entity?it represents a real world object.

    54.What is a conceptual data model?

    A conceptual data model is concerned with the general description of the database without concernfor how the data may be organized.

    55.What is two phase locking?It is a most common mechanism that is used to control concurrency in two phases for achieving theserializability. The two phases are Growing and Shrinking.1) A transaction acquires locks on data items it will need to complete the transaction. This is calledgrowing phase. A transaction may obtain lock but may not release any lock.

    2) One lock is released no other lock may be acquired. This is called shrinking process. Atransaction may release locks but may not obtain any new locks.56.What is projection?

    The projection of a relation is defined as projection of all its tuples over a set of attributes. it yieldsvertical subset of the relation. The projection operation is used to trim the number of attributes in

    the resultant relation or to reorder attributes.57. What are the different phases of transaction?

    Different phases are Analysis phase

    Redo Phase Undo phase

    58.. What is Relational Algebra?It is procedural query language. It consists of a set of operations that take one or two relations asi d d l i