114
SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 1/114 Note: This question-bank contains three sections. Section-A contains 1 mark Multiple Choice Objective type questions. Section-B contains 5 marks subjective questions. Section-A contains 10 marks subjective questions. Section – A 1 Marks Questions [QUESTIONS 1 TO 83] [PAGE 1 TO 9] MULTIPLE CHOICE OBJECTIVE TYPE QUESTION Q1. In the relational modes, cardinality is termed as: (A) Number of tuples. B) Number of attributes. (C) Number of tables. (D) Number of constraints. Q2. Relational calculus is a (A) Procedural language. (B) Non- Procedural language. (C) Data definition language. (D) High level language. Q3. The view of total database content is (A) Conceptual view. (B) Internal view. (C) External view. (D) Physical View. Q4. Cartesian product in relational algebra is (A) a Unary operator. (B) a Binary operator. (C) a Ternary operator. (D) not defined. Q5. DML is provided for (A) Description of logical structure of database. (B) Addition of new structures in the database system. (C) Manipulation & processing of database. (D) Definition of physical structure of database system. Q6. ‘AS’ clause is used in SQL for (A) Selection operation. (B) Rename operation. (C) Join operation. (D) Projection operation. Q7. ODBC stands for Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

  • Upload
    vonga

  • View
    273

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 1/80

Note: This question-bank contains three sections.Section-A contains 1 mark Multiple Choice Objective type questions.Section-B contains 5 marks subjective questions.Section-A contains 10 marks subjective questions.

Section – A 1 Marks Questions[QUESTIONS 1 TO 83] [PAGE 1 TO 9]

MULTIPLE CHOICE OBJECTIVE TYPE QUESTION

Q1. In the relational modes, cardinality is termed as:(A) Number of tuples. B) Number of attributes.(C) Number of tables. (D) Number of constraints.

Q2. Relational calculus is a(A) Procedural language. (B) Non- Procedural language.(C) Data definition language. (D) High level language.

Q3. The view of total database content is(A) Conceptual view. (B) Internal view.(C) External view. (D) Physical View.

Q4. Cartesian product in relational algebra is(A) a Unary operator. (B) a Binary operator.(C) a Ternary operator. (D) not defined.

Q5. DML is provided for(A) Description of logical structure of database.(B) Addition of new structures in the database system.(C) Manipulation & processing of database.(D) Definition of physical structure of database system.

Q6. ‘AS’ clause is used in SQL for(A) Selection operation. (B) Rename operation.(C) Join operation. (D) Projection operation.

Q7. ODBC stands for(A) Object Database Connectivity. (B) Oral Database Connectivity.(C) Oracle Database Connectivity. (D) Open Database Connectivity.

Q8. Architecture of the database can be viewed as(A) two levels. (B) four levels.(C) three levels. (D) one level.

Q9. In a relational model, relations are termed as(A) Tuples. (B) Attributes(C) Tables. (D) Rows.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 2: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 2/80

Q10.The database schema is written in(A) HLL (B) DML(C) DDL (D) DCL

Q11.In the architecture of a database system external level is the(A) physical level. (B) logical level.(C) conceptual level (D) view level.

Q12.An entity set that does not have sufficient attributes to form a primary key is a(A) strong entity set. (B) weak entity set.(C) simple entity set. (D) primary entity set.

Q13.In a Hierarchical model records are organized as(A) Graph. (B) List.(C) Links. (D) Tree.

Q14.In an E-R diagram attributes are represented by(A) rectangle. (B) square.(C) ellipse. (D) triangle.

Q15.In case of entity integrity, the primary key may be(A) not Null (B) Null(C) both Null & not Null. (D) any value.

Q16.The language used in application programs to request data from the DBMS is referred to as the

(A) DML (B) DDL(C) VDL (D) SDL

Q17.A logical schema(A) is the entire database.(B) is a standard way of organizing information into accessible parts.(C) describes how data is actually stored on disk.(D) both (A) and (C)

Q18.Related fields in a database are grouped to form a(A) data file. (B) data record.(C) menu. (D) bank.

Q19.The database environment has all of the following components except:(A) users. (B) separate files.(C) database. (D) database administrator.

Q20.The language which has recently become the standard for interfacing applicationprograms with relational database system is

(A) Oracle. (B) SQL.(C) DBase. (D) 4GL.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 3: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 3/80

Q21.The way a particular application views the data from the database that the application uses is a

(A) module. (B) relational model.(C) schema. (D) sub schema.

Q22.In an E-R diagram an entity set is represent by a(A) rectangle. (B) ellipse.(C) diamond box. (D) circle.

Q23.A report generator is used to(A) update files. (B) print files on paper.(C) data entry. (D) delete files.

Q24.The DBMS language component which can be embedded in a program is(A) The data definition language (DDL). (B) The data manipulation language (DML).(C) The database administrator (DBA). (D) A query language.

Q25.A relational database developer refers to a record as(A) a criteria. (B) a relation.(C) a tuple. (D) an attribute.

Q26.Conceptual design(A) is a documentation technique.(B) needs data volume and processing frequencies to determine the size of the database.(C) involves modelling independent of the DBMS.(D) is designing the relational model.

Q27.The method in which records are physically stored in a specified order according to a key field in each record is

(A) hash. (B) direct.(C) sequential. (D) all of the above.

Q28.A subschema expresses(A) the logical view. (B) the physical view.(C) the external view. (D) all of the above.

Q29.Count function in SQL returns the number of(A) values. (B) distinct values.(C) groups. (D) columns.

Q30.Which one of the following statements is false?(A) The data dictionary is normally maintained by the database administrator.(B) Data elements in the database can be modified by changing the data dictionary.(C) The data dictionary contains the name and description of each data element.(D) The data dictionary is a tool used exclusively by the database administrator.

Q31.An advantage of the database management approach is

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 4: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 4/80

(A) data is dependent on programs.(B) data redundancy increases.(C) data is integrated and can be accessed by multiple programs.(D) none of the above.

Q32.A DBMS query language is designed to(A) support end users who use English-like commands.(B) support in the development of complex applications software.(C) specify the structure of a database.(D) all of the above.

Q33.It is possible to define a schema completely using(A) VDL and DDL. (B) DDL and DML.(C) SDL and DDL. (D) VDL and DML.

Q34.The method of access which uses key transformation is known as(A) direct. (B) hash.(C) random. (D) sequential.

Q35.Data independence means(A) data is defined separately and not included in programs.(B) programs are not dependent on the physical attributes of data.(C) programs are not dependent on the logical attributes of data.(D) both (B) and (C).

Q36.The statement in SQL which allows to change the definition of a table is(A) Alter. (B) Update.(C) Create. (D) select.

Q37.E-R model uses this symbol to represent weak entity set ?(A) Dotted rectangle. (B) Diamond(C) Doubly outlined rectangle (D) None of these

Q38.SET concept is used in :--(A) Network Model (B) Hierarchical Model(C) Relational Model (D) None of these

Q39.Relational Algebra is(A) Data Definition Language. (B) Meta Language(C) Procedural query Language (D) None of the above

Q40.Key to represent relationship between tables is called(A) Primary key (B) Secondary Key(C) Foreign Key (D) None of these

Q41._______ produces the relation that has attributes of R1 and R2(A) Cartesian product (B) Difference(C) Intersection (D) Product

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 5: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 5/80

Q42.The file organization that provides very fast access to any arbitrary record of a file is

(A) Ordered file (B) Unordered file(C) Hashed file D) B-tree

Q43.DBMS helps achieve(A) Data independence (B) Centralized control of data(C) Neither (A) nor (B) (D) both (A) and (B)

Q44.Which of the following are the properties of entities?(A) Groups (B) Table(C) Attributes (D) Switchboards

Q45.In a relation(A) Ordering of rows is immaterial (B) No two rows are identical(C) (A) and (B) both are true (D) None of these.

Q46.Which of the following is correct:(A) a SQL query automatically eliminates duplicates.(B) SQL permits attribute names to be repeated in the same relation.(C) a SQL query will not work if there are no indexes on the relations(D) None of these

Q47.It is better to use files than a DBMS when there are(A) Stringent real-time requirements. (B) Multiple users wish to access the data.(C) Complex relationships among data. (D) All of the above.

Q48.The conceptual model is(A) dependent on hardware.(B) dependent on software.(C) dependent on both hardware and software .(D) independent of both hardware and software.

Q49.What is a relationship called when it is maintained between two entities?(A) Unary (B) Binary(C) Ternary (D) Quaternary

Q50.Which of the following operation is used if we are interested in only certain columns of a table?

(A) PROJECTION (B) SELECTION(C) UNION (D) JOIN

Q51.Which of the following is a valid SQL type?(A) CHARACTER (B) NUMERIC(C) FLOAT (D) All of the above

Q52.The RDBMS terminology for a row is(A) tuple. (B) relation.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 6: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 6/80

(C) attribute. (D) degree.

Q53.Which of the following operations need the participating relations to be union compatible?

(A) UNION (B) INTERSECTION(C) DIFFERENCE (D) All of the above

Q54.The full form of DDL is.?(A Dynamic Data Language (B) Detailed Data Language(C) Data Definition Language (D) Data Derivation Language

Q55.Which of the following is an advantage of view?(A) Data security (B) Derived columns(C) Hiding of complex queries (D) All of the above

Q56.Which of the following is a legal expression in SQL?(A) SELECT NULL FROM EMPLOYEE;(B) SELECT NAME FROM EMPLOYEE;(C) SELECT NAME FROM EMPLOYEE WHERE SALARY = NULL;(D) None of the above

Q57.Which database level is closest to the users?(A) External (B) Internal(C) Physical (D) Conceptual

Q58.Which are the two ways in which entities can participate in a relationship?(A) Passive and active (B) Total and partial(C) Simple and Complex (D) All of the above

Q59.Which of the following is a comparison operator in SQL?(A) = (B) LIKE(C) BETWEEN (D) All of the above

Q60.A set of possible data values is called(A) attribute. (B) degree.(C) tuple. (D) domain.

Q61.Which of the operations constitute a basic set of operations for manipulating relational data?

(A) Predicate calculus (B) Relational calculus(C) Relational algebra (D) None of the above

Q62.Which of the following is another name for weak entity?(A) Child (B) Owner(C) Dominant (D) All of the above

Q63.Which of the following database object does not physically exist?(A) base table (B) index

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 7: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 7/80

(C) view (D) none of the above

Q64.NULL is(A) the same as 0 for integer(B) the same as blank for character(C) the same as 0 for integer and blank for character(D) not a value

Q65.Which of the following is record based logical model?(A) Network Model (B) Object oriented model(C) E-R Model (D) None of these

Q66.A data dictionary is a special file that contains:(A) The name of all fields in all files.(B) The width of all fields in all files.(C) The data type of all fields in all files.(D) All of the above.

Q67.A file manipulation command that extracts some of the records from a file is called

(A) SELECT (B) PROJECT(C) JOIN (D) PRODUCT

Q68.A primary key is combined with a foreign key creates(A) Parent-Child relation ship between the tables that connect them.(B) Many to many relationship between the tables that connect them.(C) Network model between the tables that connect them.(D) None of the above.

Q69.In E-R Diagram derived attribute are represented by(A) Ellipse (B) Dashed ellipse(C) Rectangle (D) Triangle

Q70.The natural join is equal to :(A) Cartesian Product(B) Combination of Union and Cartesian product(C) Combination of selection and Cartesian product(D) Combination of projection and Cartesian product

Q71.Which one of the following is not true for a view:(A) View is derived from other tables.(B) View is a virtual table.(C) A view definition is permanently stored as part of the database.(D) View never contains derived columns.

Q72.A primary key if combined with a foreign key creates ?.(A) Parent-Child relationship between the tables that connect them.(B) Many to many relationship between the tables that connect them.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 8: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 8/80

(C) Network model between the tables that connect them.(D) None of the above.

Q73.In E-R Diagram relationship type is represented by(A) Ellipse (B) Dashed ellipse(C) Rectangle (D) Diamond

Q74.Hierarchical model is also called(A) Tree structure B) Plex Structure(C) Normalize Structure (D) Table Structure

Q75.To delete a particular column in a relation the command used is:(A) UPDATE (B) DROP(C) ALTER (D) DELETE

Q76.The ______ operator is used to compare a value to a list of literals values that have been specified.

(A) BETWEEN (B) ANY(C) IN (D) ALL

Q77.function divides one numeric expression by another and returns the remainder..(A) POWER (B) MOD(C) ROUND (D) REMAINDER

Q78.A data manipulation command the combines the records from one or more tables is called

(A) SELECT (B) PROJECT(C) JOIN (D) PRODUCT

Q79.In E-R diagram generalization is represented by(A) Ellipse (B) Dashed ellipse(C) Rectangle (D) Triangle

Q80._________ is a virtual table that draws its data from the result of an SQL SELECT statement.

(A) View (B) Synonym(C) Sequence (D) Transaction

Q81.The method of access which uses key transformation is known as(A) Direct (B) Hash(C) Random (D) Sequential

Q82.A table joined with itself is called(A) Join (B) Self Join(C) Outer Join (D) Equi Join

Q83._________ data type can store unstructured data(A) RAW (B) CHAR

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 9: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 9/80

(C) NUMERIC (D) VARCHAR

Q84.Which two files are used during operation of the DBMS(A) Query languages and utilities(B) DML and query language(C) Data dictionary and transaction log(D) Data dictionary and query language

ANSWERS1. A2. B3. A4. B5. C6. B7. D8. C9. A10. C

DBDCAAABAB

DABBCCACAB

CDBBDACACC

ACDCCDBDBA

DADCDBABDD

CACDADAABD

CADACABCDA

81. B82. B83. A84. C

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 10: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 10/80

Section – B 5 Marks Questions[QUESTIONS 1 TO 98] [PAGE 10 TO 54]

Q1. What is data base management system?Ans.Database Management System (DBMS): A data base management system is a software that enable users to create and maintain database. For example every individual or a company has a data, which is to be stored and manipulated. i.e. adding new data, deleted unwanted data or making changes in the existing data. The DBMS is thus a general-purpose system that facilities the process of defining, constructing and manipulation database for various applications.Defining a database involves specifying the types of data to be stored in the database, along with its description.Constructing the database is the process of storing the data itself on some storage medium, which is controlled by the DBMS.Manipulating the database includes functions like querying the database to retrieve specific data, updating the data to reflect changes and generating reports from the data.

Q2. What are various advantages of DBMS?Ans.Advantages of DBMSReduction of redundancies: Centralized control of data by the DBA avoids unnecessary duplication of data and effectively reduces the total amount of data storage as required.Shared data:A database allows the sharing of data under its control by any number of application programs or user.IntegrityCentralized control can also ensure that checks are incorporated in the DBMS to provide data integrity. Data integrity means data value being entered for storage could be checked to ensure that they fall within a specified range and are in correct format.Security Data is vital important to an organization and should be accessed by unauthorized person. Data independenceData independence is are considered from two points of view:Logical Level: This level of abstraction describes what data is stored in the database, and what relationships exist among them.Physical Level: This is lowest level of abstraction and describes how the data is actually stored. At the physical level complex low-level data structures are described in detail.Controlling the data redundancy Duplication of same data in different files Wastage of storage space, since duplicated data is stored. Time in entering data again and again is wasted. Elimination of Inconsistency In the file processing system information is duplicated throughout the system. So changes made in one file may be necessary be carried over to another file.

Q3. What are the various disadvantages of DBMS?

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 11: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 11/80

Ans.Disadvantages of DBMS: A significant disadvantage of DBMS system is the cost. In addition to the costs of purchasing or developed the software, the hardware was to be upgraded to allow for the extensive programs and the workspaces required for the execution and storage. An additional cost is that of migrant from a traditionally separate application environment to an integrated one. While centralization reduces duplication, the lack of duplication requires that the database be adequately backed up so that in the case of failure the data can be recovered. Backup and recovery operations are fairly complex in DBMS environment, and become worse in a multi-user database system.

Q4. Explain the file management system along with its disadvantages.Ans.File Management SystemThe file management system was the first method used to store data in computerized database. The data item is stored in one large file. A particular relationship cannot be drawn between the items other than the sequence in which it is stored. If a data item has to be located, the search start at the beginning and item are checked sequentially till the required item is foundDisadvantage of File management system1. Locating and retrieving a record is very tedious process because of its sequential access method.2. Altering the file has to be read and rewritten. It involves writing the new data item into a temporary file, adding this item as a last field each record deleting the original file and renaming the temporary file

Q5. Explain the Architecture of DBMS.Ans.Architecture of DBMS:

1. INTERNAL LAYER OR NATIVE LAYER: The internal view is the view about the actual Physical storage of data. It tells us how data is stored physically in the database. It also tells the physically implementation of the database to achieve optimal runtime performance and storage space utilization. 2. CONCEPTUAL OR PHYSICAL LAYER: The conceptual view describes the structure of the whole database for a community of users. The conceptual view represents all the

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

External level

Conceptual level

Internal level

Hardware

End user

End useEnd user

Page 12: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 12/80

database entities, their relationships, information on data, constraints on data, security and integrity information etc. 3. EXTERNAL OR LOGICAL LAYER: This external level includes a number of user views, which describe the part of the database that is a particular user group is interested in and hides the rest of the database from the user group.

Q6. Discuss the similarities and difference between DBMS and RDBMS.Ans. Difference between DBMS and RDBMS are : DBMS stand for Database Management System, which consist n number of tables there is no relationship between another tables. RDMBS stand for Relational Database Management System, which having the relationship with other tables. The Relationship between tables in DBMS is Physical and the relationship in RDBMS is Logical. .DBMS does not support Data Integrity and RDBMS support Data integrity. RDBMS support Structural Independence and Advanced Query Capabilities while DBMS does not support this. DBMS does not support Security while RDBMS supports Security on Databases. You cannot share data between Clients and server in DBMS as sharing is possible in RDBMS between Tables.The similarities between DBMS and RDBMS are : Both the database management system provides manipulation tools to manipulate data. Both databases support Reports Generation and storing of huge amount of data. Both databases support SQL (structured query Languages)

Q7. Define Data Integrity.Ans. Data integrity ensures that the values entered in the database attributes are accurate and lying within specified range. For example the age of the employees will be in the range of 18 to 70 years.To define an integrity constraint, include a constraint clause in a Create Table or Alter Table Statement. The Constraint clause has two systematic forms;Table Constraint: - The table constraint syntax is part of the table definition. Integrity Constraint defined with this syntax can impose rules on any columns in the table. The Table Constraint syntax can appear in a Create Table or Alter Table Statement.Column Constraint: - This constraint Syntax is part of a column definition. Integrity Constraint defined with this syntax can impose rules only on the column in which it is defined.

Q8. Explain Entity Relationship model.Ans.Entity Relationship Model: Entity set is represented by E-R relationship and is mapping from one entity set to another. The E-R model is usually shown on pictorially using entity relationship diagram. The entities and the relationship between them are shown using the following convention: - An entity is shown as rectangle A diamond represents the relationship among a number of entities, which are connected to the diamond by lines. The attribute shown as ovals are connected to the entities relation by lines. Diamond, ovals and rectangle are labeled the type of relationship existing between the entities is represented by giving the cardinality of the relationship on the joining the relationship to the entities.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 13: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 13/80

The Pictorial representation is as follows:

Rectangle Diamond

Oval Line

Q9. What are the various database models? Explain.Ans.Database Models:Hierarchical database modelNetwork database modelRelational database modelHierarchical database model

In this model, data storage is in the form of parent-child relationship. The origin of data tree is the root data located at different levels along a particular branch from the root is called the node. The last node in the series is called the leaf. This model supports one to many relationships.DisadvantageIt is not possible to enter a new level into the system as and when such a need arises the entire structure has to be remapped. Another disadvantage is that this model does not support many to many relationships.Network database modelThe data is shared rather than being repeated. The main idea behind the NDS model is to bring about many to many relationships. The relationship between the different data item is called as sets. This system also uses a pointer to locate a particular record.DisadvantageThe use of pointer leads to complexity in the structure. As a result of the increased complexity mapping of related data become very difficult.Relational database modelDr. E.F. Codd first introduced the Relational database model in 1970. The data and relationship of data is represented by a collection of tables. No pointers or links are used to define the relations. Many columns can be added without any difficulty. It is very flexible. One of reasons behind the success of relational model is simplicity. It is very easy to understand data when presented in the form of a table.Each data field is considered as a column and each record is considered as row of table. Department detail in one table and their employee detail into other table

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 14: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 14/80

Dept Code Dept name PhoneD101 PTU 546566D102 MDU 567889

Employee code Emp. Name Address Dept code1 Vijay 187,Patiala D1012 Ajay 435,patiala D1023 Rajinder 34,chandiagh D101

Q10.What do you mean by Referential Integrity?Ans. Referential Integrity: Referential Integrity means that exists a foreign key in a relation. Each foreign key fields data value must match the primary key’s data value in the other relation that references. A referential integrity constraint designates a column or combination of columns as a foreign key and establishes a relationship between that foreign key and a specified primary or unique key called the referenced key. In this relationship, the table containing the foreign key is called the child table and the table containing the referenced key is called the parent table.Q11.What is normalization or what is the need for normalization? Write its advantages.Ans. Normalization: Normalization is widely used in relational database. It is the process of splitting the relations into relations with fewer attributes by minimizing the redundancy of data and minimizing insertion, deletion and updating anomalies. Normalization may be defined as a step-by-step reversible process of transforming an unnormalized relation into relations with progressively simpler structures. Normalization is based on the concept of normal forms. Advantages of Normalization Allow to create separate tables that can be joined easily. Data loss can be taken care as key columns cannot be deleted. Faster sorting and index creation. Improves the performance of INSERT, UPDATE, and DELETES statements. Fewer NULL values and less opportunity for inconsistency, which increase database compactness.

Q12.Write about the various rules to apply normalization on the database.Ans.Normalization rules:There are a few rules that can help you achieve a sound database design: 1) A table should have an identifier. The fundamental rule of database design theory is that each table should have a unique row identifier, a column or set of columns that can be used to distinguish any single record from every other record in the table. Each table should have an ID column, and no two records can share the same ID value. The column or columns serving as the unique row identifier for a table are the primary key of the table. 2) A table should store only data for a single type of entity. Attempting to store too much information in a table can prevent the efficient and reliable management of the table’s data. 3) A table should avoid null able columns. Tables can have columns defined to allow null values. A null value indicates that there is no value. While it can be useful to allow null values in isolated cases, If you have a table with several null able columns and several of the rows have null values in the columns. 4) A table should not have repeating values or columns. The table for an item in the database should not contain a list of values for a specific piece of information. If you find that

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 15: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 15/80

you need to store a list of values in a single column, or if you have multiple columns for a single piece of data (au_lname1, au_lname2, and so on), you should consider placing the duplicated data in another table with a link back to the primary table.

Q13.Explain various normal forms, their anomalies and advantages.Ans.The normal forms of normalizations are as follows:First Normal Form: If the values in the relation instances are atomic for every attribute in the relation, the relation is said to be in the first Normal form. Any relation is called atomic if the element of the relation is indivisible. I.e. cannot be broken down further. Anomalies of first normal form:1. Repetition of information2. Inability to represent certain informationSecond Normal Form: If every non-key attribute of a relation schema is fully functionally dependent on the key then relation is said to be in 2nd NF. 2nd NF is also in 1NF.Those relation are not in 2NF can be converted into 2NF using the following procedure.For each functional dependency, which is not fully functionally dependent on the key, form new relations using its attributes.The attributes on the right hand side of the above FDs are eliminated from the original relation.Advantages:Redundancy, which was pointed out the 1NF, does not exist in 2NF.Certain information can also be retrievedAnomalies: Transitive Dependency is a Functional dependency XY in a relation scheme R is a transitive dependency if there is a set of attributes Z that is neither a candidate key nor a subset key of R and both XZ and Z—Y holds. A general case of transitive dependency is as follows:A, B, C are three columns in a tableIf C is related to BIf B is related to A Then C is related to A.Third Normal Form: A relation is set to be 3nf if it is in 2nf and the no known key attribute of the relation is transitively dependent on the primary key. In 3nf the 2nf relation are converted into the smaller relations such that no relation contains any transitive dependency involving key attributes.Anomalies:It may contain redundancy of data.

Q14.What are views and schemas in a database?Ans.After a table is created and populated with data it may become necessary to prevent all users from accessing all columns of a table, for data security reasons. For this purpose it is required to make several tables with different number of columns. It will make data redundant to reduce redundancy. Oracle allows the creation of an object called a view. View is stored as definition in oracle’s system catalogue. When reference is made to a view, its definition is scanned the base table is opened and the view created on top of base table.Schema: The database schema is used to describe the conceptual organization of the data base system. This organization is defined during the design process, usually using the data definition language provided by the particular software vendor. Any user, with the appropriate

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 16: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 16/80

privileges, can create objects in his or her own schema. Some schema objects are tables, synonyms, indexes, sequences and views.

Q15.Discuss the Design of distributed DBMS. How are they useful?Ans. A database all of whose components is not localized on a single location but instead is stored on different sites on a network is known as a distributed database. The database management systems in such cases are equipped with network support and strict control mechanisms. Moreover the database management system itself may be located at more than one site. The distributed system is designed in such a way, though, that the users are unaware of the distribution. They access data as they are interacting with a local database. It is the responsibility of the distributed database management system to see it to that the requested data is brought to the user from wherever it is residing now. The process is totally transparent to the users..Q16.What is Relational Algebra? How is relational calculus applied? Give suitable examples.Ans. Relational Algebra is a procedural language. It specifies the operations to be reformed on existing relations in derived result relation. It defines the complete schema or each of the result relations. The relational algebraic operation can be divided into basic set-oriented operations and relational- oriented operations. Basic operations Basic operations are the traditional set operations: union, difference, intersection and Cartesian product. Two relations are union compatible if they have the same parity and one to one correspondence of the attributes with the corresponding attributes defined over the same domain.ExampleIn the example to follow, we utilize two relations P & Q. R is computed result relation.P:

ID Name101 Jones103 Smith104 Lalonde107 Even110 Drew112 Smith

Q:Id Name103 Smith104 Landloe106 Byron110 Drew

If we assume that P & Q are two union compatible relations, then the union of p and q is the set theoretic union of p and q.The resultant relation, r=P U Q The result relation R contains tuples that are in either p or q or in both of them.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 17: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 17/80

Q17.What is E-R Diagram? What are its Various Components?Ans. Entity Relationship Diagram: Entity set is represented by E-R relationship and is mapping from one entity set to another. The E-R model is usually shown on pictorially using entity relationship diagram.

Creating an entity relationship diagram1. Identify the entities.2. Define the identifiers.3. Define the relationships4. Determine cardinality of the relationship.5. Determine descriptive attributes.6. Create the ER-diagram.7. Review and refine the record.

The Entity-Relationship(E-R) diagram represents the logical structure of a database by using entities and relationships between the entities. You can graphically represent an E-R model by using Entity-Relationship[(ERD) diagram.The entity-relationship model is based on a perception of the world as consisting of a collection of basic objects (entities) and relationships among these objects. An entity is a distinguishable object that exists. Each entity has associated with it a set of attributes describing it. E.g. number and balance for an account entity. A relationship is an association among several entities. e.g. A cust_acct relationship associates a customer with each account he or she has. The set of all entities or relationships of the same type is called the entity set or relationship set. Cardinality:It is simply the no of tuples (rows )in a relation(table)Cardinality is very important database properties. Cardinality is a relationship property that indicates the number of related instances an entity may have. An entity may have zero, one, or many related entity instance.Another essential element of the E-R diagram is the mapping cardinalities, which express the number of entities to which another entity can be associated via a relationship set. An E-R diagram can express the overall logical structure of a database graphically: Rectangles: represent entity sets. Ellipses: represent attributes. Diamonds: represent relationships among entity sets. Lines: link attributes to entity sets and entity sets to relationships. The E-R model is beneficial for a database Designer in various ways, which are:The constructs used in the E-R model can easily be transformed into relational tables.Simple and easy to understand and is, therefore used by a database designer to communicate a database design to the user accessing the database.Is used as a design plan by a database developer to implement a data model is database management system.

Q18.Explain Advantages and Disadvantages of relational model.Ans.Advantages of Relational Model1.Simplicity: The relational database model is very simple and easy to design and implement at the logical level. All the relations are designed in a tabular manner, which helps the user to concentrate on the logical view of the database.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 18: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 18/80

2.Flexible: The relational database provides flexibility that allows changes to database structure easily.3.Data Independence: The structure of database can be changed without having to change any applications that were based on that structure.4.Structural Independence: relational database is only concerned with data and not with the structures, which improves performance.5.Query Capability: In this model the queries are based on logical relationships and processing those queries does not require predefined access paths among the data i.e. pointers.Disadvantages1. It provides the limited ability to deal with images spread sheets etc.2. This model is very costly because it requires latest hardware technology.3. Mapping objects to relational database can be difficult skill to learn 4. Relational model is not suitable for huge databases but suitable for small databases.

Q19.Explain the duties of DBA.Ans.Data base administrator is the person who makes the strategic and policy decisions regarding the data of the enterprise. DBA is the person who provides the necessary technical support for implementing those decisions. Thus DBA is responsible for the overall control of the system at technical level.1. Defining the conceptual schema: It is the job of DBA to decide exactly what information is to be held in the database. In other words, to identify the entities of interest to the enterprise and to identify the information to be recorded about these entities.2. Defining the internal schema: The DBA must also decide how the data is to be represented in the stored database. In addition he must also define mapping between the internal and conceptual schema.3. Liaising (communication) with users: It is the business of DBA to liaise with users, to ensure that data they require is available and to write the necessary external schema. 4. Defining security and integrity rules: Security and integrity rules can be regarded as part of the conceptual schema. The conceptual DDL should include facilities for specifying such rules.5. Defining backup and recovery procedures: Once the database is designed, whole working of enterprise is dependent on it. So it becomes important to take regular backups of database. In the event of damage the data can be recovered from the most recent backup.

Q20.What is a relationship? How many types of relationships are in RDBMS?Ans. Relationship among Data: - A relational ship is defined as “an association among entities”. A relationship type is an association of entity types, while a relationship instance is an association of entity instance is an association of entity instances. A relationship may associate an entity with itself. The three different types of relationship may recognized among various data stored in the database are;ONE TO ONE: - Consider an example a set of students in a class. Each student can have only one roll no. Similarly each roll number can be associated only with one student. This is the case of a one to one relationship.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

AssignedStudent1 Rollno-1

Page 19: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 19/80

Many to One: - One student can register for only one particular course at a time. Where as a number of students could register for the same course. This can be illustrated with the following figure;

Many to Many: - A vendor can sell a number of items and many vendors can sell a particular item. The following Figure will clear it to you.

Q21.What are the Different Levels of Data Abstraction?Ans.Since many database system users are not computer trained, developers hide the complexity from users through different levels of Data abstraction, to simplify users’ interactions with the system:Physical Level: The lowest level of abstraction describes how the data are actually stored. At the physical level complex low-level data structures are described in detail.Logical Level: The Next higher level of abstraction describes what the data are stored in the database, and what relationships exist among those data. The entire database is thus described in terms of a small number of relatively simple structures. Although implementation of the simple structures at the logical level may involve complex physical level structures, the user of the logical level does not need to be aware of this complexity. Database administrator who must decide what information is to be kept in the database.View Level:- The highest level of abstraction describes only part of the entire database. Despite the use of simpler structures at the logical level, some complexity remains because of the large size of the database. Many users of the database system will not be concerned with all this information. Instead such users need to access only a part of the database. So that their interaction with the system is simplified, the view level of abstraction is defined. The system may provide many views for the same database.Q22.What are the Various Components of DBMS? Ans. The Major components of DBMS are:i) Data Definition Language Complier: (DDL Complier) : This complier converts the data definition statements in to a set of tables. These tables contain the metadata concerning the database and are in a form that can be used by other components of the DBMS.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Register Course

Student 1

Student 2

Student 3

Vendor 1

Vendor 2 Vendor 4

Vendor 3

Page 20: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 20/80

ii) Data Manager: It is the central software component of the DBMS. This converts operations in the user's queries from the user's logical view to a physical file system. Data manager is also responsible for interfacing with the file system, tasks of enforcing constraints to maintain the consistency and integrity, security etc. It also ensures backup and recovery operations, concurrency control etc. iii) File Manager: Its main responsibility is fare the structure of the file and management of file space. It is also responsible for locating the block containing the required record. iv) Disk Manager: This is the post of OS of the host computer and all physical input and output operations performed by it. It transfers the block or page request by the file manager so that the later need not be concerned with the physical characteristics of underlying storage media. v) Query Processor: The query processor is used to interpret the online user's query and convert it into an efficient series of operations.

Q23.Explain the concept of existence dependency.Ans. If the existence of entity X depends on the existence of entity Y, then X is said to be existence dependent on Y. operationally if Y is deleted, so is X. Entity Y is said to be a dominant entity and X is said to be subordinate entity.The participation of an entity set E in a relationship set R is said to be total if every entity in E participates in at least one relationship in R. If only some entities in E participate in relationship in R, the participation of entity set E in relationship R is said to be partial.

Q24.What is the structure of Selection? Explain.Ans.The select statement is most frequently used SQL statement. The Select statement is used primarily to query or retrieve data from the database. The basic syntax of select statement is

Select column1, column2, column3, and column-N From table-1 …table-N

[Where condition][Order by column-name [Ask | Desc] [, column-name [ Asc | Desc]…]]; The select clause lists the subset of attributes or columns to retrieve, From clause lists the tables from which to obtain the data. The column mentioned in the select clause must be a column of the tables listed in from clause. The where clause specifies the conditions or conditions that need to be satisfied by the tuples or rows of the tables indicated in the from clause The order by clause indicates the criterion or criteria used to sort rows that satisfy the where clause. The order by clause only affects the display of the data retrieved not the internal ordering of the rows within the tables.

Q25.What is the structure of Projection? Explain.Ans.The projection operator is also a unary operator. Whereas the selection operator chooses a subset of the rows of the relation, the projection operator chooses a subset of columns.The basic syntax is

Select column1, column2, and column3 column-N From table-1 …table-N

[Where condition][Order by column-name [Asc | Desc] [, column-name [ Asc | Desc]…]];

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 21: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 21/80

The select clause lists the subset of attributes or columns to retrieve, From clause lists the tables from which to obtain the data. The where clause specifies the conditions or conditions that need to be satisfied by the tuples. The order by clause indicates the criterion or criteria used to sort rows that satisfy the where clause. For example: To retrieve the data of employee’s name, title and department the command isSelect name, title, dept from employee where dept=’accounting’;

Q26.What are table instance charts used to depict.Ans. The table instance chart (TIC) are used by the oracle corporation, describes in a detailed manner each entity, its attributes and the relationships in which the entity may participate whether the relationship of the entity is to itself or to some other entities. The symbols used in TIC to represent entries are PK Primary KeyFK Foreign KeyFK1 FK2 Two FKs within the same tableNN Not Null columnU Unique columnU1, U1 Two Column those are unique in combination

The format of TIC of Table Projects is shown as belowTable Name: Project

Column Name P_ID Project_Name Project_mgr_idKey Type PkNulls/Unique NN, UFK Ref. TableFK. Ref. ColumnData Type Character Character CharacterMaximum Length 7 25 9Sample Data P001 Railway Bridge 986756

Q27.Given the following business rules, create the appropriate E-R diagram for each of the specified relationships.a. A company operates four departments.b. Each department employs employees.c. Each of the employees may or may not have one or more dependents.d. Each employee may or may not have an employment history.Ans:

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 22: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 22/80

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Empno

CompanyAddress

HavingDepartment

Sales Marketing Accounts Personal

Deptno Deptno Deptno Deptno

Employee Emp. History

Empno Empname history

Emp.Histor

y

Works in

Department

DeptNameLocation

DeptNo

EmployeesEmpName

Job

Empno

EmpHistory History

EmpName

Page 23: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 23/80

Q28.What are the different types of database end users? Discuss the main activities Of each user.Ans.The users of a database management system fall into many categories according to the role they play in the database environment. The users may belong to the following categories:End-User: the users who utilize the data stored in the database and the derived processed information are referred to as end-users. Most of the time as a manager you would fall into this category of users.Operator: The user who performs data entry and carry out allied activities are operators.Programmer: The advanced users who developed and create application programs that interact with the database are database programmer.Database Designer: The users who design the structure of a database suitable for a given application are called database designer.Data analyst: The users who retrieve data stored in a database, analyze it statistically or otherwise and deduce inference are called data analyst.Database administrator: The users who are overall in-charge of the administrative control of a database system are called database administrator. They are responsible for the smooth operation of database.

Q29.Define the following with respect to an ER diagram. Explain the manner in which each is mapped to a table. Illustrate with an example.

(A) Relationship set (B) AggregationAns:(A) Relationship set –The concept of grouping relationships of same type into one group.Relationships are categorized by its degree

(B) Aggregation: - Aggregation is an abstraction in which relationship sets are treated as higher level entry sets used for purpose of participation in other relationship.The process of combining entity sets and their relationships to form a high level entity set so as to represent relationships among relationships is called aggregation. The higher-level entity, set is treated as a single entity set like others.

Ternary relationship (incorrect representation) Of ER Diagram

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Student

Name rollno

class marks

visitLibrary

rollno bname

cost

University Interview

RESULT _IN

Job_offer

Applicant

Page 24: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 24/80

Ternary relationship (correct representation) Of ER Diagram

Q30.How can you differentiate between SQL and SQL * PLUS?Ans.SQL vs. SQL * Plus: SQL is a standard language common to all relational databases. SQL is a database language used for storing and retrieving data from the database. Most Relational Database Management Systems provide extensions to SQL to make it easier for application developers. SQL is further divided into the following categories.Data Definition Language (DDL) statements These are used to create, alter, or drop schema objects. Main DDL statements are CREATE, ALTER and DROP. We will discuss each of these in detail in next section.Data Manipulation Language (DML) statements These are used to query and manipulate data in existing schema objects. Main DML statements are INSERT (to insert rows in the existing table), SELECT (to retrieve data from an existing table), DELETE (to delete rows from an existing table) and UPDATE (to update records of an existing table. Transaction Control Statements These are used to manage changes managed by DML statements. Mainly used Transaction Control statements are ROLLBACK, COMMIT and SAVEPOINT.SQL * Plus is an Oracle specific program, which accepts SQL commands and PL/SQL blocks and executes them. SQL*Plus enables manipulation of SQL commands and PL/SQL blocks. It also performs many additional tasks as well. It provides a an interface to the database users for interaction with oracle.

Q31.What are logical operators in SQL? Explain with examples.Ans. These operators are AND, OR, and NOT.The AND operator: The AND operator retrieves only those rows whose satisfy the both conditions.

Select column list from table name where condition1 and condition 2;The OR operator: The OR operator retrieves only those rows that satisfy either or both conditions. The syntax of using OR with two Boolean conditions looks like this.Select column list from table name where condition /OR condition2The NOT operator: The NOT operator is used to specify the columns values that are used to exclude the record from display. The NOT acts only on one condition. It is a unary operator. The syntax for using NOT with a where condition looks like:Select column list from table name where colname not in(list of values from table);Q32.Explain various advantages of using SQL.Ans.ADVANTAGES OF SQL 1. SQL is a high-level language that provides a greater degree of abstraction than procedural languages. It is designed in such manner so that the programmer can specify what data is needed but need not specify how to retrieve it.2. SQL enables end-users and systems personnel to deal with a different types of database management systems

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

University Interview

RESULT IN

Job_offer

Applicant

Page 25: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 25/80

3. Applications written in SQL can be easily ported across systems. Such porting could be required when the underlying Database Management System needs to be Upgraded or changed. 4. SQL as a language is independent of the way it is implemented internally. A query returns the same result regardless of whether optimizing has been done with indexes or not. This is because SQL specifies what is required . 4. 5. The language while being simple and easy to learn can handle complex situations. 6. The expected results are well defined. The language has a sound theoretical base and there is no ambiguity about the way a query will interpret the data and produce the result. 7. SQL is not merely a query language. The same language can be used to define data structures, control access to the data and delete, insert and modify occurrences of the data. 8. All SQL operations are performed at a set level. One select statement can retrieve multiple rows; one modify statement can modify multiple rows. This ‘set-at-a time’ feature of SQL makes it more powerful than the ‘record-at-a-time’ processing techniques employed in languages like say COBOL.

Q33.Write down components of SQL in details. (very important)Ans.SQL is an interface between the Oracle and User. Sql provides creation of data selection of data and updation of data. SQL statements are divided into four categories.Data Definition Language (DDL) statements These are used to create, alter, or drop schema objects. Main DDL statements are CREATE, ALTER and DROP.Data Manipulation Language (DML) statements dml statements are used to perform various operations on the database. DML statements are INSERT, SELECT, DELETE and UPDATETransaction Control Statements the tcl statements manage the change made by dml statements and group dml statements into transactions the various tcl statements are commit, rollback.Embedded SQL Statements These statements are embedded with the procedural language C, JAVA, and COBOL etc.

Q34.Explain Different Constraints in Oracle.(very important)Ans.Following Constraints can be defined on a field of a table:-1. Primary Key 2. Foreign Key 3. Not Null 4. Default Value5. Unique6. CheckNote:-Default & Not Null Constraints can only be defined at column level, Applying Not Null In a TableWhile creating tables, if a row lacks a data value for a particular column, that value is said to be null. Columns of any data type may contain null values unless the column was defined as not null. E.g.Create table client master (client no varchar2 (6), name varchar2 (20) not null, city varchar2 (15), state varchar2 (15) not null);Defining not null after creating a tableAlter table client master modify (name varchar2 (20) not null, state varchar2(15) not null);Defining Unique In A Table

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 26: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 26/80

The purpose of unique key is to ensure that information in the column for each record is unique.E.g.Create table emp (emp_code varchar2 (5),name varchar2(15) not null ,addr varchar2(25), phone number(8) unique,d_o_j date default sysdate ); Defining Default ConstraintAt the time of cell creation a ‘default value’ can be assigned to a column. When the user is loading a record with values he can leave the cell empty, the DBA will automatically load this cell with the default value specified. The data type of the default value should match the data type of the column.E.g. Create table s_order( s_no varchar2(6),s_date date default sysdate, dely_addr varchar2(25), client_no varchar2(6));Defining Check ConstraintsUse the check constraints when you need to enforce integrity rules that can be evaluated based on a logical expression. Never use check constraints if the constraint can be defined using the not null, primary key or foreign key constraints.Create table salespeople (snum number(10),sname varchar2(20),City varchar2(25),comm number(2,2) check(comm<100));Defining Primary Key At Column LevelCreate table product_master (Product_no varchar2(6) PRIMARY key ,Description varchar2(15) not null,R_lvl number(8),S_Price number(8,2),C_Price number(8,2));The foreign key constraint  ·Rejects an insert or update of a value, if a corresponding value does not currently exists in the primary key table. ·Rejects a delete, if a corresponding record currently exists in the primary key table.·Must reference a table not a view.·Must not reference the same column more than once in a single constraint.Syntax to Define Foreign Key At Column LevelCreate table s_o_details (S_Orderno varchar2(6),Product_no varchar2(6)references Product_master (product_no ) ,Qty_ordered number (6));

Q35.Explain Different methods of inserting records into the table.Ans.First Method:

Insert into Emp (empno, ename, dname, salary, phone)values (609,’rajesh’,’accounts’,5000,2219334);

Second Method: -Insert into emp values (609,’rajesh’,’accounts’, 5000,2219334);Third Method: -Insert into Emp Values (&empno, ‘&ename’, ‘&ename’, &salary, &phone);

Q36.How can a table be created in SQL? Write syntax of using update and select command.Ans. Create a Table: - The table command is used to create a table.Example: -Create table student (Name char (20) Not NULL, Fname char (20) Not Null, Rno number (4));Update Table: - The update statement is used to modify or update an existing row of a table.Example: -Update student set result =”Pass” where Rno = 28;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 27: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 27/80

Select: - Display the data records of a table * is used to get all the columns of a particular table.Example: -Select * from Book-Table;Select B.Name, Title, Author, Price from Book Table;

Q37.What are commonly built in DataTypes available in Oracle?Ans.Data Types are very important in Oracle Oracle treats values of one datatype differently from values of another dataype. Oracle provides a number of built-in datatypes as well as user defined datatypes. Here we are taking some simple built-in datatypes, user defined datatypes.Commonly used built in DataTypes in Oracle are: CHAR (size): It stores character or alphanumeric data, where maximum number of characters stored is equal to the number of bytes defined by size. When a table is created with CHAR datatype column, for every data value entered in that column Oracle reserves the number of bytes equal to number of bytes defined by size in the memory. VARCHAR2 (size): Similar to CHAR datatype, VARCHAR2 is also used for storing the alphanumeric data, where maximum length is equal to the number of bytes specified by size.Default value for a VARCHAR2 column is zero character and the maximum allowed is 4000 bytes. It is must to specify the maximum length for a VARCHAR2 column. This maximum must be at least 1 byte. NUMBER(p,s) It can store a number with precision p and scale s. This means that it can store a number having maximum number of digits after decimal point equal to s and before decimal point equal to p. A Number datatype can store zero, positive, and negative fixed and floating-point numbers with 38 digits of precision and range of scale from –84 to 127. LONG datatype column is capable of storing a variable-length character string containing up to 2 gigabytes, or 2 31 -1 bytes. For memory reservation LONG column have the characteristics similar to VARCHAR2 column. The length of LONG values may be limited by the memory available on your computer. A table can’t contain more than one long data type column. Thus as far as possible, use of long datatype columns should be avoided. DATE: DATE data type stores the date and time information, in the format: century, year, month, day, hour, minute, and second. Default value for time is 12:00:00 AM (midnight) and default value for date is first day of current month. SYSDATE is a date datatype, gives the current date and time. SYSDATE + 1 will give the date of tomorrow. RAW (SIZE), LONG RAW this is used to store the binary data, where data is not to be interpreted by Oracle. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of binary data, for which the interpretation is dependent on the use. Like Long datatype Long Raw datatype imposes a lot of restrictions, so as far as possible its use should be avoided. ROWID is a pseudocolumn that stores the address of each row of table in the database. Datatype ROWID stores a hexadecimal string representing the address of row.

Q38.Write down the features of Oracle 8i.Ans.Oracle8i Enterprise edition adds several high-end features and options for mission-critical OLTP and data warehousing applications, apart from the usual features of standard edition of Oracle8i. Oracle8i Enterprise Edition for Windows NT is a development and deployment platform for the Internet. Oracle8i Enterprise Edition for Windows NT features include the following:

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 28: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 28/80

a) A built-in Java Virtual Machine that lets you store and run Java code within an Oracle database. The Java VM provides a runtime environment for Java objects. It fully supports Java data structures, method dispatch, exception handling, language-level threads, and the entire core Java class libraries.b) Support for the Common Object Request Broker Architecture (CORBA), the Internet Inter-ORB (Object Request Broker) Protocol (IIOP), and Enterprise Java Beans. CORBA objects communicate using OMGs Internet Inter-ORB Protocol (IIOP), the standard for communication between and among distributed objects running on the Internet, intranets, and in enterprise computing environments. Oracle8i integrates a Java-based CORBA 2.0 compliant Object Request Broker (ORB) that provides users with the ability to call into and out of the database server using CORBA's IIOP. c) Support for SQLJ, a programming syntax that lets you embed SQL statements in Java programs.d) Integration with the Component Object Model (COM) and Microsoft Transaction Server. e) Component software has recently been promoted as the next evolution in software development. The growth of object-oriented programming and distributed objects are proof of this industry-wide trend. f) The scripting of components enables you to reuse code that is pre-built and pre-tested. The reuse of code fulfills one of the key objectives of software development: shorter development cycles and reduced time to market. g) Oracle COM Automation feature has been created to enable you to use COM-based to customize and enhance the functionality of the Oracle8i database on Windows NT.

Q39.What is operator define the is operator, in and between operator ?ANS There are different types of operators in sql. All operators are used with the where clause. Operators are used to execute the potential record’s Column value against a specified value. If evaluation is true then it display the records.IS Operator-The equal (=) operator is used to compare the value with another values of the tables. This operator cannot be used if the argument is null in that case we use IS operator in place of the (=) equal operator. The is operator is used with null argument.Lets take an example of this:-Sql> Select EMPID, ENAME,WAGES from employeeWhere name=’SHAM’ || wages IS NULL;OutputEMPID ENAMEWAGES1 Deepak2 Sham 120003 Ram 100004 RohitIN operator-The IN operator is used to retrieve the value from the column of the table those values are define in the query.ExampleSql> Select empid, Ename from employee where ename IN( ‘Sham’,’Ram’);OutputEMPID ENAME2 SHAM

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 29: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 29/80

3 RAMBetween operator - It compare the column value with two arguments. If the value is within a range of the arguments then condition is true. If the value equals either high or low range the condition is also true. The condition is false if value is outside the range.This operator consist of two keywords.First is BetweenSecond is ANDExampleSql> Select Ename,wages from employee where wages between 10000 AND 15000;Output Ename wagesSham 12000Ram 10000

Q40.What is the function of Commit and AutoCommit?Ans.COMMIT: This command will make all transaction permanent in the database. After inserting records just enter the commit on SQL prompt and Enter. All the records will make permanent. Every time you have to give this command after inserting records.

Syntax is SQL> Commit;AUTOCOMMIT: This command also makes all transaction permanent in the database. Only difference between commit and AutoCommit is that there is no need to insert again and again commit command. Just one time you enter AutoCommit command it will store all data permanently automatically.

Syntax is SQL> SET AutoCommit on;

Q41.What do you mean by View?Ans.A view is a query of one or more tables that provides another way of presenting information.You can perform insert, update, delete, and operations on the view. The view is also called virtual table. Views don’t actually stored data rather they derive their data from the tables on which they are based refer to as the base tables of the views.A view is a customized arrangement of data contained in one or more tables (or other views). It can be defined as a database object that logically represents one or more tables. A view can be defined as a window to an existing database table. A view takes the output of a query and treats it as a table; therefore, a view can be thought of as a "stored query" or a "virtual table". You can use views in most places where a table can be used. It is an imaginary table and contains no data in it. Data is extracted from already existing tables. Hence it does not occupy any table space. Consequently a view always shows up-to-date data.

Q42.What is snapshot or materialized view?Ans. The term “snapshots” and “materialized view “are synonymous. Both refer to a table that contains the results of a query of one or more tables, each of which may be located on the same or on a remote database. The tables in the query are called master tables or detail tables. The databases containing the master tables are called the master databases. A snapshot is a read only table. No updates can take place on the snapshot. Only the master table can be updated, snapshot reflects changes, only if refreshed by the snapshot refresh cycle..

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 30: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 30/80

Q43.Explain various types of joins.(Important)Ans.Equi join: An equi join is a join with a join condition containing an equality operator. An equi join combines rows that have equivalent values for the specified columns. Example:-The equi join returns the name, department no and name of the department in which that employee works.EMPENAMEEmpno SALARY DEPTNO Navjeet 1 2500 2Rubal 2 1200 3Sharan 3 3400 2Munish 4 2300 1Rishi 5 4332 2Neeta 6 4234 4DEPTDEPTNO DNAME ------ ---------- 1 accounts 2 sales 3 quality 4 marketing 5 hraSelect ename, empno, dname from emp, dept where emp.deptno=dept.deptno;ENAME Empno DNAME-------------------- --------- ----------rubal 4 accountsnavjeet 1 salesprince 3 salesrishi 5 salesheena 2 qualityneeta 6 marketingSelf-Join: A self-join is a join of a table to itself. This table appears twice in the FROM clause and followed by table aliases that qualify column names in the join condition. To perform a self-join oracle combines and returns rows of the table that satisfy the join condition.ManagerEmpno ENAME MGRNO 1 navjeet 3 2 gurmeet 1 3 sharan 2 4 ravneet 3 5 nidhi 3Select m1.ename"employee",m2.ename"manager" from manager m1,manager m2 where m1.mgrno=m2.empno;Cross-join or Cartesian join: -If two tables in a join query have no condition, Oracle returns their Cartesian product. Oracle combines each row of one table with each row of other. It is rarely useful.For example the Cartesian product of tables , each with 10 rows , has 100 rows.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 31: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 31/80

Example: Select ename,dname from emp,dept;

DEPTDEPTNO DNAME------ ---------- 1 accounts 2 sales 3 quality 4 marketing 5 hra

EMPENAME Empno SALARY DEPTNONavjeet 1 2500 2Heena 2 1200 3Prince 3 3400 2Rubal 4 2300 1Rishi 5 4332 2Neeta 6 4234 4

Outer JoinAn equi join combines rows that have equivalent values for the specified columns from the multiple tables. In Outer join if we want to display the records that are outer to the joined table we use outer join with (+) sign after the table name who’s outer you want to display. Outer join will show the records, which are common in two tables but also show record from the outer table, which is uncommon in one table.e.gTo display the records outer in dept tableSelect empno, ename, emp.deptno, dept.dname from emp, dept where emp.deptno(+)=dept.deptno;To display the records outer in employee tableSelect empno, ename, emp.deptno, dept.dname from emp, dept where dept.deptno(+)=emp.deptno;Q44.Explain the Set Operators used in RDBMS (Oracle).Ans.Set operators combine the results of two queries into a single result_queries containing set operators are called compound queries.Union ClauseThe user can put together multiple queries and combine their output using the union clause. The union clause merges the output of two or more queries into a single set of rows and columns. E.g.

Select all the clients and salesman in the city of BombaySELECT salesman_no “id” , name FROM salesman_master WHERE city=”bombay”UNIONSELECT client_no “id”, name FROM client_master WHERE city= ‘bombay’;

Suppose we want to find the name of employees who works in Marketing department and Sales Department.

Select Ename from employee where dept=’Marketing’UnionSelect Ename from employee where dept=’Sales’

Intersect Clause

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 32: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 32/80

The user can put together multiple queries and combine their output using the intersect clause. The intersect clause outputs only rows produced by both the queries intersected i.e. the output in an intersect clause will include only those rows that are retrieved by both the queries. Select name from studentIntersectSelect name from stu_marks;Minus ClauseThe user can put together multiple queries and combine their output using the minus clause. The minus clause outputs only rows left in the first query.  E.g.: - SELECT product_no FROM product_master

MINUSSELECT product_no FROM sales_order_details;

Q45.What are Synonyms? What are their uses?Ans. A synonym is an alternative name for a table, view, sequence, procedure, stored function package, materialized view, java class object, or another synonym. 1.Simplifies SQL coding: if underlying object is renamed or moved, only synonym needs to be redefined. Application using the synonyms needs no modification.2.Improves database security: it masks the underlying object’s actual name, owner and locationProvide public access to an oracle object: private and public synonyms can be created. All the users of a database share public synonyms.

Q46.Explain following terms in detail with example.1 SUB QUERIES RETURNING SINGLE VALUE2 SUB QUERIES RETURNING MULTIPLE VALUESAns. SUB QUERIES RETURNING SINGLE VALUE :- In a nested query statement the inner query can return a single value or multiple values. Now depending upon the no of values returned by the sub query in a nested query the whole query should be framed. For example, consider the previous query. Since for a particular passenger there can be only one passenger_id hence the inner query returns only one value. Because of single value return by the inner query we use the (=) operator, which matches for a single value only. One can also use other relational operator like >, >=, <, <=, and! = For sub queries that returns single value.

e.g. Select address from teacher where exists (select * from course where

count(student_id)>40;

SUB QUERY RETURNING MULTIPLE VALUES :- (=) operator, which tests for single value only. It cannot work in case of multiple rows returned by the nested query. For example, let us try to find the airline_name for all those flights that passes through the route, with sd_code of ‘ndln’.SELECT airline_name FROM airlines_detail WHEREairline_id = (SELECT airline_id FROM flights_detailWHERE sd_code = 'ndln');The output of this command is

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 33: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 33/80

airline_id = (SELECT airline_id FROM flights_detailERROR at line 2:ORA-01427: single-row subquery returns more than one rowIn the above example, since the inner query returns multiple rows the (=) operator fails to handle the result. Hence in such cases when sub queries returns multiple values, we should use special operators like ANY, ALL, IN or NOT IN between the comparison operator and the subquery.

Q47.What are Usage and Advantages of View? Explain It with Detail.Ans.View are used because they provide a lot of advantages such as To provide an additional level of table security by restricting access to a predetermined set of rows and/or columns of a table. To hide data complexity. A single view might be defined with a join, which is a collection of related columns or rows in multiple tables. However, the view hides the fact that this information actually originates from several tables. To simplify commands for the user. Views allow users to select information from multiple tables without actually knowing how to perform a join. To present the data in a different perspective from that of the base table. The columns of a view can be renamed without affecting the tables on which the view is based. If the table has four columns and fifth columns added to the table, the view's definition is not affected and all applications using the view are not affected. To express a query that cannot be expressed without using a view. A view can be defined that joins a GROUP BY view with a table, or a view can be defined that joins a UNION view with a table. To save complex queries. For example, a query could perform extensive calculations with table information. By saving this query as a view, the calculations can be performed each time the view is queried.

Q48.What is the effect of Null on aggregate functions? Explain with examples.Ans. When we want to implement some of the aggregate functions like Sum, Avg or Count etc. on numeric data in a column from a table and that column contain some of the Null values then aggregate function will skip those values from the column and calculate rest of the values from the column. For exampleIn a table if it contains values like

Rollno Name Course Fees101 Raj kumar DCA 6000102 Mohan MCA103 Kiran Deep BSC 6000104 Rani MCA105 Mukesh PGDCA 7500

Suppose we want to calculate sum of total fees from the table but the fees column contain null values so command isSelect count(*), sum(fees) from studentThis query will display the result as Count(*) Sum(Fees) 5 19500

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 34: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 34/80

Q49.How will you eliminate duplicates from the result of Select statement? Explain with example.Ans.We can eliminate duplicate values from the result of Select statement using a Distinct Keyword. This keyword will eliminate duplicate values from the result query. E.g if table Student contains duplicate record then to eliminate duplicate values from the select statement the Query is:

Table: StudentRollno Name Course Fees101 Raj kumar DCA 6000101 Raj kumar DCA 6000103 Kiran Deep BSC 6000101 Raj kumar DCA 6000105 Mukesh PGDCA 7500

Select Distinct * from Student;The query will Result the following display :

Rollno Name Course Fees101 Raj kumar DCA 6000103 Kiran Deep BSC 6000105 Mukesh PGDCA 7500

Q50.What is the purpose of Group By, having and Order By clause in select statement.Ans.The rows displayed from a query do not have any specific order weather ascending or descending. But if you want them in ascending or descending order in a particular field then you can control this order for the selected rows. This is done by adding the clause order by to the select commande.g Select emp_code, emp_name, Desig, Basic from employee where basic>2500 order by emp_nameorSelect emp_code, emp_name, Desig, Basic from employee where basic>2500 order by emp_name descThe Group by clause will allow you form group based on the specified condition. The having clause defines criteria used to eliminate certain groups from the output just as the where clause does for individuals rows. E.gSelect deot_code, sum(basic) from employee group by dept_code having sum(basic)>13000.

Q51.What are updateable and non-updateable views? How views can be updated.Ans. Updateable views are those views in which data manipulation (i.e insert, update or Delete operations) can be done. For exampleCreate view v1 as select empno, ename, job from emp;This will create a view named v1 from table emp;To Update view the command is:Update v1 set job=’Manager’ where empno=101;Non-Updateable views are the views which are Read only views or in which data manipulation (i.e insert, update or Delete operations) can not be done.,for example.Create view v2 as select empno, sum(salary),avg(salary),count(*) from emp;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 35: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 35/80

Q52.Give example using SQL for retrieval using exists.Ans.The exists operator is useful in the situation in which you are not interested in the column values returned by sub queries. This operator returns true if sub query returns at least on row and false if no rows are returned by the sub query. Lets find the addresses of teachers who teach in class consisting of at least 40 students: the query will be:Select address from teacher where exists (select * from course where count(student_id)>40)

Q53.Give example-using SQL for retrieval using ANY.Ans.The ANY operator compares a value to each value returned by a sub query. It evaluates to true

If there exists at least one row selected by the sub query for which the comparison holds. It evaluates to FALSE if the query returns no rows. It must be proceeded by =, !=, >, <, >= and <=. Suppose we want to find the name of the students who is older than at least one teacher who teaches DBMS course.Select st_name from student where age>any(select t_age from teacher where teach=’DBMS’);

Q54.Explain the architecture of the PL/SQL in Detail. Also explain Character set of PL/SQL (Very Important).Ans.PL/SQL Stands for Procedural Language/SQL. PL/SQL is a development tool that extends the features provided in the SQL database language. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks.Allows using general programming tools with SQL, for example: loops, conditions, functions, etc.This allows a lot more freedom than general SQL, and is lighter-weight than JDBC (Java Database Connectivity) is used to connect Java programs with databases.PL/SQL BLOCKPL/SQL code is built of Blocks, with a unique structure.There are two types of blocks in PL/SQL:1.Anonymous Blocks: have no name (like scripts). can be written and executed immediately in SQLPLUS can be used in a trigger.2. Named Blocks: Procedures Functions Anonymous Block Structure:DECLARE (optional)/* Here you declare the variables you will use in this block */BEGIN (mandatory)/* Here you define the executable statements (what the block DOES!)*/EXCEPTION (optional)/* Here you define the actions that take place if an exception is thrown during the run of this block */END; (mandatory) /

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 36: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 36/80

CHARACTER SET OF PL/SQL: When we write a PL/SQL program as lines of text using a specific set of characters. The PL/SQL character set includes.The upper and Lowercase Letters A….Z, a…..zThe number 0…9Tabs, spaces, and carriage returnsThe symbol is not case sensitive, so lowercase letters are equivalent to corresponding uppercase letters except within string and character literals.Q55.What is PL/SQL? Explain it in Detail and also Explain Structure of PL/SQL.Ans.PL/SQL is a 4GL (fourth generation) programming language. It offers all features of advanced programming language such as portability, security, data encapsulation, information hiding etc. A PL/SQL program may consists of more than one SQL statements, while execution of a PL/SQL program makes only one call to Oracle engine, thus it helps in reducing the network overheads. Structure of PL/SQL:PL/SQL is a block structure language. This means a PL/SQL program is made up of blocks, where block is a smallest piece of PL/SQL code having logically related statements and declarations. A block consists of three sections namely: Declare Begin and Exception followed by an End statement. Declare sectionDeclare section declares the variables, constants, processes, functions etc., to be used in the other parts of program. It is an optional section.Begin sectionIt is the executable section. It consists of a set of SQL and PL/SQL statements, which is executed when PL/SQL block runs. It is compulsory section.Exception SectionThis section handles the errors, which occurs during execution of the PL/SQL block. This section allows the user to define his/her own error messages. This section executes only when an error occurs. It is an optional section.End Section

This section indicates the end of PL/SQL block.

Q56.Explain the following terms.1 Delimiters 2 IdentifiersAns.DELIMITERS: - A delimiter is a simple or compound symbol that has a special meaning to PL/SQL. Simple symbol consists of one character, while compound symbol consists of more than one character. + - * / = > < ; % ` , ( ) @ : “Compound symbol delimiters legal in PL/SQL are as follows:

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 37: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 37/80

!= ~= ^= <= >= := ** .. || << >>IDENTIFIERS: - Identifiers are used in the PL/SQL programs, to name the PL/SQL program items as constants, variables, cursors, cursor variables, subprograms etc. Identifiers can consists of alphabets, numerals, dollar signs, underscore and number signs only. An identifier must begin with an alphabetic letter optionally followed by one or more characters (permissible in identifier). An identifier can’t contain more than 30 characters. Some of the valid identifiers are as follows:A -- identifier may consist of a single characterA1 -- identifier may consist of numerals after first characterShare$price – dollar sign is permittede_mail -- underscore is permittedphone# -- number sign is permitted

Illegal;DECLAREbegin CHARACTER; -- illegal; causes compilation errorLegal;DECLAREbegin_session CHARACTER; -- legal

Q57.Explain Different data types available in PL/SQL.Ans.Every constant and variable has a datatype. A datatype specifies the space to be reserved in the memory, type of operations that can be performed and valid range of values. PL/SQL supports all the built in SQL datatypes. PL/SQL provides some other datatypes. Some commonly used PL/SQL datatypes are as follows:BOOLEAN:- One of the mostly used datatype is BOOLEAN. A BOOLEAN datatype is assigned to those variables, which are required for logical operations. A BOOLEAN datatype variable can store only logical values, i.e. TRUE, FALSE or NULL. %TYPE: -The %TYPE attribute provides the datatype of a variable or database column. In the following example, %TYPE provides the datatype of a variable:balance NUMBER(8,2);minimum_balance balance%TYPE;In the above example PL/SQL will treat the minimum_balance of the same datatype The %TYPE attribute is particularly useful when declaring variables that refer to database columns. %ROWTYPE :- The %ROWTYPE attribute provides a record type that represents a row in a table (or view). The record can store an entire row of data selected from the table. In the example below emp_rec is declared as a record datatype of emp table. emp_rec can store a row selected from the emp table.emp_rec emp%ROWTYPE;

Q58.What are features of PL/SQL?Ans. PL/SQL is completely portable, high-performance transaction processing language that offers the following advantages: Support for SQL: SQL has become the standard database language because it is flexible, powerful, and easy to learn. SQL is a non-procedural meaning that you can state what you want to do without stating how to do it. A few English-like commands such as Insert, Update and Delete make it easy to manipulate the data stored in a relational database.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 38: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 38/80

Support for Object Oriented Programming: Object types are an ideal object-oriented modeling tool, which you can use to reduce the cost and time required to build complex applications. Better Performance: PL/SQL also improve performance by adding procedural processing power to Oracle tools. Using PL/SQL a tool can do any computation quickly and efficiently without calling on the oracle server. This saves time and reduces environments. Higher Productivity: PL/SQL adds functionality to non-procedural tools such as oracle forms and Oracle reports. With PL/SQL in these tools, you can use familiar procedural constructs to build applications. Integration with Oracle: Both PL/SQL and Oracle are based on SQL. PL/SQL supports all the SQL data types. The %TYPE and %ROWTYPE attributes further integration PL/SQL with the data dictionary.

Q59.Explain Procedure and Function in Details.Ans.A procedure is a subprogram that performs some specific task, and stored in the data dictionary. A procedure must have a name so that it can be invoked or called by any PL/SQL program that appears within an application. Procedures can take parameters from the calling program and perform the specific task. When a procedure is created, the Oracle automatically performs the following stepsThe syntax for creating a procedure is follows:CREATE OR REPLACE PROCEDURE [schema.] procedurename [(argument {IN, OUT, IN OUT} data type …)] {IS, AS}[Local variable declarations]BEGINExecutable statementsEXCEPTIONException handlersEND [procedurename];1. Compiles the procedure2. Stores the procedure in the data dictionaryThe oracle compiles the PL/SQL block. If an error occurs during creation of procedure, Oracle displays a message that procedure is created with compilation errors, but it doesn’t display the errors. To see the errors following statement is used.SELECT * FROM user_errorsFUNCTION: -Function is similar to procedure except that it must return one and only one value to the calling program. The syntax for function is as follows:CREATE OR REPLACE FUNCTION [schema.] functionname [(argument INdatatype, ….)] RETURN datatype {IS,AS}[local variable declarations];BEGINExecutable statements;EXCEPTIONexception handlers;END [functionname];

Q60.What is Cursor? Also explain their attributes.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 39: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 39/80

Ans.A cursor is a private area for SQL operations, used by the Oracle engine. This is an area in the memory in which a parsed statement and other information for processing the statements are kept. Oracle uses work areas to execute SQL statements and store processing information. A cursor is a PL/SQL construct. It allows naming a work area and accessing its stored information. In oracle cursor is used for easy processing to handle multiple record queries. Cursors are constructs that enable the user to name a private memory area to hold a specific statement for access at a later time.Attributes of CursorImplicit cursors have certain attributes that can be used to access information about the most recently executed SQL statement using cursor. The implicit cursor attributes are as follows:%ISOPEN%NOTFOUND%FOUND%ROWCOUNT%ISOPEN: -This attribute always returns false for implicit cursor, because Oracle automatically closes the implicit SQL cursor after executing its associated SQL statement.%NOTFOUND : -The %NOTFOUND attribute returns true if DML statement like INSERT, UPDATE and DELETE affects no rows and do not have a return value, else it evaluates to false. It is used to determine that no rows are processed in an SQL statement. %FOUND: - The %FOUND attribute is just the logical reverse of %NOTFOUND attribute. This attribute also returns Boolean variable. It evaluates to true if DML statements like INSERT, UPDATE and DELETE affects one or more rows or SELECT returns one row. %ROWCOUNT: - The %ROWCOUNT is used to determine the no of rows that are processed by the DML statement. It returns the number of rows affected by INSERT, UPDATE and DELETE statement or returned by a SELECT INTO statement. It returns zero if the SQL statement affects or returns no rows.

Q61.What are Advanced Data Types? Also explain following data types in detail.1) Internal LOB2) External LOBAns.There is another category of data types available in Oracle called Large Objects or LOBs. As the name suggests, these data types can store large amount of data. These advanced data types can store unstructured information such as sound clips, video files up to 4 gigabytes in size. They allow efficient, random, piece-wise access to data. The LOB types store values, which are known as locators. These locators store the location of large objects. LOB values can be operated upon through the use of locators.Types of LOBOracle8 regards LOBs are defined into two types internal LOBs and external LOBs, also referred to as BFILEs (binary files).a. INTERNAL LOB: Internal LOBs, as their name suggests, are stored inside database table spaces in a way that optimizes space and provides efficient access. You can recover internal LOBs in the event of transaction or media failure, and any changes to an internal LOB value can be committed or rolled back. Internal LOB Data typesThere are three SQL data types for defining instances of internal LOBs:BLOB: - A LOB whose value is composed of unstructured binary data up to 4GB in length, stored in database.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 40: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 40/80

CLOB: - A LOB whose value is composed of character data up to 4GB in length, stored in database.NCLOB: - A CLOB column that supports a multi byte character set.External LOB: -External LOBs are also known as BFILES. They are large binary data objects stored in operating system files outside the database table spaces. BFILEs are located on tertiary block storage devices such as CD-ROM, PhotoCDs and DVDs. External LOB does not participate in transactions. Any support for integrity and durability must be provided by the underlying file system as governed by the operating system.External LOB Data typeThere is one external SQL LOB data type:BFILE A LOB whose value is composed of binary ("raw") data, and is stored outside the database table spaces in a server-side operating system file.

Q62.Explain following commands in detail with example.1 CREATING USER2 CHANGING PASSWORDAns.CREATING USER: - New user in Oracle can be created using either Enterprise Manager or SQL *DBA or the SQL command CREATE USER. The syntax for creating user is as shown below. CREATE USER USERNAMEIDENTIFIED [BY PASSWORD | EXTERNALLY |GLOBALLY AS ‘EXTERNAL_NAME’][DEFAULT TABLESPACE TABLESPACE ][TEMPORARY TABLESPACE TABLESPACE ][QUOTA { N [ K | M ] UNLIMITED } ON TABLESPACE ][PROFILE PROFILE ][ACCOUNT [LOCK | UNLOCK ][PASSWORD EXPIREA new User must have a name and a method of identification. The other parameters all have default values. The name is used as login, while the password is for user authentication. For example, a user can be created as follows:SQL > CREATE USER VMC IDENTIFIED BY 12345;CHANGING PASSWORD:- Password can be easily altered by the DBA (Database Administrator) or through the security manager. This can be done in SQL using the command ALTER USER. The exact syntax is as follows:SQL > ALTER USER USERNAME IDENTIFIED BY NEWPASSWORDFor example, the password for the user VMC can be changed to ‘abc123’ as follows:SQL > ALTER USER VMC IDENTIFIED BY abs123;

Q63.What are Database Security and Privileges? Also explain how they Work.Ans.Provides extensive security features in order to safeguard the user’s information from both unauthorized access and intentional damage. Granting or revoking privileges on a user-by-user and privileges-by-privileges basis provides this security. A user can also grant privileges directly to other users, of course restricted only to those privileges that the user has.How it Work: -1 SQL mostly provides an environment that requires to recognize and differentiate between

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 41: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 41/80

e various user of the system.2 Each user in an oracle database has a specific authorization.3 Commands are interpreted and permitted on the basis of information associated with the authorization associated with the ID of the user issuing the command.4 The DBA creates the users and gives them privileges.5 Privileges determine whether or not a user can execute a given command or a command when acting on specific group of data.6 There are different types of privileges corresponding to different types of operations.

Q64.What do you understand by RowID?Ans.Row id is created by oracle for each new row in every table; it is a Pseudo column that has a value for every row in a table. The RowID gives us the physical address of a row and is fastest way to access any row. The RowID contain 3 bits of information, they are:1 The Blocks within the database2 Row # within the Blocks3 Database file IDAn example could be 000088C. 0002The RowID has three important uses1. The fastest path to any row2. A way of speeding the commit process in application code.3. Unique identifiers of any given row.*END;

Q65.Explain Raise Application Error.Ans.Oracle provides a procedure named raise_application_error, that allows programmers to issue user-defined error messages.Syntax: - raise_application_error(error_number,message);WhereERROR_NUMBER : is a negative integer in the range -20000... -20999MESSAGE:is a character string up to 2048 bytes in length.Example:CREATE TRIGGER check_qty_on_handBEFORE UPDATE OF qty_on_handON product_master FOR EACH ROWDECLARE

new_qty number(8);BEGIN

new_qty := :new.qty_on_hand;if new_qty < 0 THEN

raise_application_error(-20001,’Quantity on hand cannot be less than 0’);END IF;END;

Q66.How can we use these LOBs?Ans. USING BLOB: A BLOB object stores data as a binary file. A variable can be initialized as BLOB data type.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 42: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 42/80

Syntax Create table company_detail (airline_id varchar2(4) not null, logo BLOB);To insert empty data in BLOB data type the following command is used.Insert into company_detail values (‘1000’, EMPTY_BLOB());Using CLOBA CLOB object stores data as character in file. It is similar to the long data type and is used to store long strings such as summary, resume etc.Alter table company_detail ADD (contract CLOB);To store empty data in contract by using EMPTY_CLOB() functionUsing BFILE BFILE is used for storage reference or file pointers to any binary file that is external to the database. Alter table company_detail add (log2 BFILE);Value can be inserted asInsert into company_detail values (‘3000’,EMPTY_BLOB (), EMPTY_CLOB (), BFILENAME (‘c:\logo’,’sa.jpg’);

Q67.Define DBMS_LOB package. Name the function and procedure provided by this package to handle LOBs?Ans.These LOB data types can be manipulated only by using DBMS_LOB package. The DBMS_LOB package provides subprograms to operate on BLOB_LOBs, CLOBs, NLOBs, BFILEs, and temporary LOBs you can use DBMS_LOB TO access and manipulation specific parts of a LOB or complete LOBs.It provides read-only operations for BFILEs. The bulk of the LOB operations are provided by this package. Subprograms provided by DBMS_LOB package.1. Append procedure: appends the contents of the source LOB to the destination LOB.2. CLOSE procedure: closes a previously opened internal or external LOB.3. Compare function: - compares two entire LOBs or parts of two LOBs.4. Copy procedure: - copies all, or part, of the source LOB to the destination LOB.5. Create temporary procedure: - creates a temporary BLOB or CLOB and its corresponding index in the user’s default temporary tablespace.6. Erase procedure: - erases all or part of a LOB.7. FILECLOSEALL: - closes all previously opened files.8. File exists: - checks if the file exists on the server.9. File getname :- gets the directory alias and file name.10. File isopen function: - checks if the file was opened using the input BFILE locators.11. File open: - open a file12. Free temporary: - frees the temporary BLOB or CLOB in the user’s default temporary tablespace.13. Get chunksize: returns the amount of space used in the Lob chunk to store the LOB value.14. Get length function: - gets the length of the LOB value.15. Instr function: - returns the matching position of the nth occurrence of the pattern in the LOB.16. isopen function :- check to see if the LOB was already opened using the input locator.17. istemporary function :- checks if the locator is pointing to a temporary LOB.18. loadfromfile proecedure :- loads BFILE DATA INTO AN INTRNAL LOB.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 43: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 43/80

19. Open procedure: - open a LOB in the indicated mode.20. Read procedure: - reads data from the LOB starting at the specified offset.21. substr function :- returns part of the LOB value starting at the specified offset.22. Trim procedure: - trims the LOB value to the specified shorter length.23. Write procedure: - writes data to the LOB from a specified offset.24. Write append: - writes a buffer to the end of LOB.

Q68.Write a PL program to find the number of elements in the table using count method.Ans.DeclareMbook student.book_issued%type;Mname student.student_name%type;Cursor c1 isSelect student.name, books_issued from student;BeginOpen c1;LoopFetch c1 into mname, mbook;Exit when cl%notfound;Dbms_output.put-Line(‘Books issued to ‘ ||’ ‘|| mname);For I in 1..mbook.countLoop Dbms_output.put_line(‘ ‘||mbook(i).book_title);End loop;End loop;Close c1;End;

Q69.Define varray and steps to create varray.Ans. Varray is an array of ordered set of data elements. All elements of a given array are of the same datatypes. Each element has an index, which is a number corresponding to the element’s position in the array. The number of elements in an array is the size of the array. Oracle arrays are of variable size, which is why they are called varray.Following steps are used to create varrayExample: - create a table department, having the columns dept_id, name, budget, and project. The column project is the nested table. This table will store the records of departments. Each project may have more than one project also populate the table with records.Steps 1 create an object for table.Create type project as object (project_no NUMBER(2), title varchar2(35), cost number(7,2))Step 2 define varray type projectlst, which stores project objectsCreate type projectlist as varray(50) of projectStep 3 finally create relational table department, which has a column of type project list Create table department (dept_id number(2), name varchar2(15),budget number(11,2), projects project list);

Step 4: -Now populate the table with recordInsert into department

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 44: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 44/80

values(30,’Accounting’,1205700,projectlist(Project(1,’DesignNewexpenseReport’,4150),Project(2,’outsourcePayroll’,16350),

Project(3,”EvaluateMergerProposal’,3150),Project(4,’auditAccount’,1225)));Update data in the tableUpdate department Set projects=projectlist(Project(1,’issue new Employee Budges’,13500),Project(2,’DevelopNewPatrol Plan’,1250), Project(3,’Inspect Emergency Exits’,1900),Project(4,’Upgrade Alarm System’,3350), Project(5,’Analyse Local Crime Stats’,825))where dept_id=60;

Q70.What are triggers and stored procedures? Explain by writing small example using Sql.Ans. A database triggers is stored PL/SQL program unit associated with a specific database table or view. The code in the trigger defines the action the database needs to perform whenever some database manipulation (INSERT, UPDATE, DELETE) takes place.Unlike the stored procedure and functions, which have to be called explicitly, the database triggers are fires (executed) or called implicitly whenever the table is affected by any of the above said DML operations. A database trigger has three parts - A triggering event A trigger constraint (Optional) Trigger actionTypes of trigger Row Triggers Statement Triggers Before Triggers After TriggersRow Triggers A row trigger is fired each time the table is affected by the triggering statement. For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement.Statement Triggers: Statement triggers are useful if the code in the trigger action does not depend on the data provided by the triggering or the rows affected.Before vs. After triggers :When defining a trigger you can specify the trigger timing, i.e. you can specify when the triggering action is to be executed in relation to the triggering statement. BEFORE and AFTER apply to both row and statement triggers. BEFORE TRIGGERS:Before triggers execute the trigger action before triggering statement. AFTER TRIGGERS:After trigger executes the trigger action after the triggering statement is executed.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 45: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 45/80

Q71.What do you mean by Grant and Revoke Permissions?Ans.Granting and Revoking PermissionsThe objects created by one user are not accessible by another user unless the owner of those objects gives such permission to other users. This permission can be given by using the grant statement and withdrawn by using revoke statement.Syntax For GRANT:-GRANT { ALTER/DELETE/INDEX/INSERT/SELECT/UPDATE }ON objectname TO username [ WITH GRANT OPTION ]; E.g.GRANT SELECT, UPDATE ON client_master TO mita ; Revoking The Permissions Given :- Permissions once given can be denied to the user using the REVOKE command. One user can revoke the permission granted to another user, if he is the owner of the object or the user had granted the permission to another user. Syntax For REVOKE:- REVOKE {ALTER/ DELETE/ INDEX / INSERT/ SELECT/ UPDATE}ON objectname FROM username;Note: - you can use the revoke command to revoke object privileges that you previously granted directly to the revoke. You cannot use the REVOKE command to perform the following operations:·      Revoke the object privileges that you did not grant to the revoke.·      Revoke the object privileges granted through the operating systemE.g:-1. Revoke delete privilege on supplier_master from florian.REVOKE DELETE ON supplier_master FROM florian;

Q72.Why is database security important for an organization? What are the potential threat points in a database system?

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 46: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 46/80

Ans. Database security means to provide authenticated access to the database using grant privileges and revoke privileges options. Database security is very important for any organization. It helps to manage the following things: 1. Secure your data from unauthorized access.2. Provide only sufficient access to any user on the specific object.3. Only valid data insertion in the database.4. Referential checks on the base table.There are different types of securities provided by RDBMS:1. Data integrity/security2. Referential integrity/security3. Object access security.Potential Threats:When no security system is used with database. There are number of problems raised by the system:1. Increase duplicacy2. No consistency in database3. Unauthorized user can access and spoil your data in the database4. Wrong results provided by the queries applied on the database

Q73.What are updateable and non-updateable views? How views are updated.Ans. View provides logical independence on the data size in the database. We can create different types of views on the same table without modifying the original structure of the table. Views are divided into two categories: Updateable Non-updateableUpdateable views: - Any modification made in the updateable view can affect on the data store in the original table. These views are normally single table views and created without using any aggregate function in select or where close.Non-updateable view: - These view are also known as read only views because these are only used to view data. They can include function in them.Syntax: Create view viewname or select * from table name

Q74.What do you mean by Transaction Processing and Concurrency management?Ans. Transaction processing is the way to process data in a database depends upon a particular transaction. The transaction can be saved or roll backed according to a specific criteria. To perform transaction processing there are three types of terms used:1. Rollback: It is used to undo all the changes made in the database. Oracle allows you to rollback an entire uncommitted transaction.2. Save Point: It is an intermediate marker within the context of a transaction. It divides the long transaction into smaller parts. It is used to conditional transact or a transaction if it is accurate, then user can commit otherwise a user can rollback the save point.3. Auto Commit: It is the process to commit the transaction after each SQL command without the user explicitly giving commits command.Concurrency means simultaneous access to same database by more than one user. When several users are accessing and perhaps changing the data at the same time, it is important top maintain integrity so that successive changes do not corrupt the data. Commit command is used to make the changes permanent and rollback is used to undo the transaction made.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 47: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 47/80

Q75.What are Sub-queries? How do you use Sub-query for deleting rows from the table?Ans. A Sub-query is a form of SQL statement that appears inside another SQL statement. It is also termed as nested query. The statements containing sub-query is called a parent statement. The rows returned by the parent statement to provide values for the condition in the where having clause in various DML statements. Sub-queries can also be used to eliminate duplicate records from same table. The following command is used:Syntax:Delete from tablename where condition E.gDelete from employee where RowID not in(Select Min(RowID) from employee Group by empId);

Q76.What are the advantages of PL/SQL over SQL? OrWhat are the differences between PL/SQL and SQL?

Ans: PL/SQL1.PL/SQL is a block-structured language. It combines SQL with procedural statements including conditional, iterative and sequential control structure.2.PL/SQL improves server performance by reducing the number of calls from application to oracle. The application pass to block of statements to oracle server at one time.3. In PL/SQL there is a provision for exception handling.4. All the SQL statements can be used in the PL/SQL block.5.PL/SQl supports declaration of variables to store intermediate results of query for using it later in PL/SQL block.

SQL1. SQL does not have any procedural capabilities. 2.Each of the SQL statements is passed to oracle server individually. 3. SQL does not provide exception handling 4.PL/SQL statements cannot be used in SQL. 5.SQL cannot store the intermediate results of a query in variable.

Q77.Write PL/SQL code to find average marks of five subjects.Ans: declare

A number;B number;C number;D number;E number;Av number;

BeginA;=&A;B:=&B;C:=&C;D:=&D;E:=&E;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 48: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 48/80

Av:=(A+B+C+D+E)/5;Dbms_output.put_line(‘average of 5 students is’||Av);End;

Q78.Write a procedure in PL/SQL to find the record of employees that belong to a particular department.Ans:Create or replace procedure record as

Cursor mycursor is Select * from dept;Dno dept%deptno%type;BeginFor I in mycursorLoopSelect deptno into dno from dept where dname=’MANAGER’;Dbms_output.put_line(‘dno’||dno);End loop;End record;

Q79.What is the Advantage of Defining View? .Ans. Views are used because they provide a lot of advantages such as To provide an additional level of table security by restricting access to a predetermined set of rows and/or columns of a table. To hide data complexity. A single view might be defined with a join, which is a collection of related columns or rows in multiple tables. However, the view hides the fact that this information actually originates from several tables. To simplify commands for the user. Views allow users to select information from multiple tables without actually knowing how to perform a join. To present the data in a different perspective from that of the base table. The columns of a view can be renamed without affecting the tables on which the view is based.

Q80.Mark the Candidate Keys in the relation of your choice?Ans. In a relation table in some cases there are more than one attribute, which is uniquely, identify each tuple in the relation. When more than one primary key exists, the alternatives are called candidate keys. Entity Relationship Diagram of One: Many Relationship

The Product Table having Candidate Keys are Pno Pname

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Product Transaction

pname Description

Qty

Orderdate

OrderNo

pno_

QtyOrdered

Page 49: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 49/80

Description Qty

The Trasaction Table having Candidate Keys are Orderno Orderdate Qtyordered Pno

Q81.Explain Two examples of user internal exceptions .Ans. Internal exceptions are raised implicitly when an error occurs in the PL/SQL block. The common error NO_DATA_FOUND is returned by the Oracle if a select into statement returns no rows. Internal exceptions are also called as predefined exceptions. Some predefined Internal exceptions are NO_DATA_FOUND ZERO_DIVIDE

Q82.Explain with example user Defined Exceptions? Ans. PL/SQL allows you to define user-defined exceptions. You can declare these exceptions only in the declare section of PL/SQL block. To declare a user defined exception you need to write a name for the exception followed by the EXCEPTION keyword.

E.g,DeclareEx EXCEPTION;BeginStatements……ExceptionWhen Ex then

………………end;/

Q83.How a Trigger is different from Procedure and Function?Ans.The difference are given below.

Trigger Procedure, function1.tabase triggers are procedures. A procedure and fuction are a sub program.2.it stored in the database. Both procedure and function are stored in the

data dictionary.3. it is implicitly executed when the contents of a table are changed.

It must have a name so that it can be called

4.it doesn’t return any value. Function necessarily returns the value.

Q84.Why are role being created for an application.Ans. In Oracle8i to provide the security of your database tables you use SQL commands. By creating a role and then controlling who has access to it, you can ensure that only certain users have access to particular database privileges. Use CREATE ROLE statement to create role, which is a set of privileges that can be granted to users or to other roles. You can use roles to administer database privileges. You can add privileges to a role and then grant the role to the user.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 50: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 50/80

Q85.Why do we use loop cursors.Ans.You can use cursor FOR loop instead of OPEN, FETCH and CLOSE statements. A Cursor FOR loop opens a cursor, fetches rows of values from the result set of a query and closes the cursor when all the rows are processed. E.g Declare cursor c1 is select * from emp order by empno;Mrow emp%rowtpe;BeginFor mrow in c1LoopDbms_output.put_line(mrow.empno||mrow.ename||mrow.job);End loop;End;

Q86.How is a package is different from procedure.Ans.The differences are given below.

package procedure1.Package is a collection of related program object like as procedure, function and cursor.

A procedure is a sub program.

2.It stored in the database. It stored in the data dictionary.3.package is divided in two part I Specification II Body

A procedure must have a name so that it can be called.

4. we can not pass any parameter in packages.

It can take parameter when we call it.

Q87.Differentiate between system and object privileges.Ans.Object Privileges allows users to perform operations such as modifying or adding the data. Object privileges can be assigned to the following types of objects: tables, views, sequnce, packages, procedures, functions, materialized views etc. For a user to be able to access an object in another user’s schema he needs the according object privileges System privileges allow users to execute Data Definition Language(DDL) or Data Manipulation Language(DML) statements such as Create, alter and Drop statements. Q88.What are Subprogram’s?Ans.Subprograms are named PL/SQL blocks that can take parameters and be invoked. PL/SQL has two types of subprograms called procedures and functions. Generally, you use a procedure to perform an action and a function to compute a value. Like unnamed or anonymous PL/SQL blocks, subprograms have a declarative part, an executable part, and an optional exception-handling part. The declarative part contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms. The executable part contains statements that assign values, control execution, and manipulate Oracle data. The exception-handling part contains exception handlers, which deal with exceptions raised during execution.

Q89.Define Truncate Command?Ans.When records are deleted from the database using Delete command, each of the record is recorded in the redo log. This can take a considerable amount of time if there is a large

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 51: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 51/80

number of a deletion. This command deletes the entire contents of the specified table without saving the records. The deleted records cannot be restored because they were not moved to the rollback tablespace. The truncated data can never be roll backed.Syntax Truncate table Tablename

Q90.Explain Range Searching and Patterns Searching?Ans. Range searching allows you to search for values in a table that exist within a range. For example, if you need to search for detail of employees which have salary between 1000 and 1500. The Query isSelect * from emp where salary>1000 and salary<1500OrSelect * from emp where salary between 1000 and 1500Similarly if you need to search for detail of employees which have salary not between 1000 and 1500. The Query isSelect * from emp where salary not between 1000 and 1500Pattern searching allows you to search for values within a table that match a pattern such as a data type or a set of characters. Pattern searching use two characters % and _. % Stands for any number of characters annd _ stands for one character. For example, if you need to retrieve the value of Ename from emp table where the first two characters of Ename are ‘MU’ then you use following query: -Select * from emp where ename like ‘MU%’Similarly if you want to retrieve the value of ename from the emp table where the second character of ename is M or N, you use following query:Select * from emp where ename like ‘_M%’ or ename like ‘_N%’

Q91.Differentiate between subquery and correlated query.Ans.A subquery is a query within a query in a SQL statement. The result of a subquery determines the result of the main query, which contains the subquery. A subquery is written either in the where clause or in the having clause of the main query. When a subquery is used in a query, the subquery is resolved first and the result of the sub-query is used to resolve the expression in the where clause of the main query. Subquery are of two types single row subquery where inner query returns single row to outer query and mltiple row subquery where inner query return multiple row to outer query. Single row subquery use =,>,<,<> to compare. Multiple row subquery use IN, Any with single row subquery operators and all with sigle row subquery operators.The syntax of subquery isSelect colmn_name from table_name where column_name logical operator (select column_name from table where conditions)You can use subquery to Insert rows in the target table Update records in the target table Create views Provide values for the conditions in the WHERE, HAVING, IN, SELECT, UPDATE and DELETE statements.In correlated subquery the inner query is executed once for each row in the outer query. In a correlated nested query the column value used in the inner query refers to the column value present in the outer query. E.g

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 52: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 52/80

Select emp_code,emp_name,basic from employee “E” where basic>(select Avg(basic) from employee where dept_code=E.dept_code)

The above query lists the detail of those employees who are getting salary greater than the average salary of their department. The E is an alias of employee table. The inner query is executed repeatedly for each row in the outer queryYou can also use a correlated subquery with a update clause. For example you can use the following correlated subquery to update emp table with dept values:Alter table emp add dname varchar2(20)Update emp a set dname=(select dname from dept where deptno=a.deptno)

Q92.How are Indexed Views created and destroyed?Ans.A view is a virtual table that consists of columns and rows of data referenced by a query. The columns and rows of a view are produced dynamically when a view is referenced. A query defining view can use various tables existing in a database. A view consist of logical data that does not exist as a stored set of data in a database. Views are used to :Restrict a user to specific columns in a table.Restrict a user to specific columns in a table.Join columns from multiple tables in a single table. You can create index on view to improve performance of the queries that frequently reference a view involving complex processing of data. The syntax to create view is:Create View v1 as select * from table where job=’manager’ order by empno;You create a complex view that contains group functions to display values from two or more tables.Syntax:Create view V2 as select d.dname,min(e.sal),max(e.sal), avg(e.sal) from emp e, dept d where e .deptno=d.deptnoGroup by d.dnameA view can be dropped and recreated. When you drop a view, all associated grants are also dropped.

How to destroy a view SQL<drop view viewname

Q93.What are the Advantages of Packages?Ans. Packages offer several advantages: modularity, easier application design, information hiding, added functionality, and better performance. Modularity :Packages let you encapsulate logically related types, items, and subprograms in a named PL/SQL module. Each package is easy to understand, and the interfaces between packages are simple, clear, and well defined. This aids application development. Easier Application Design: When designing an application, all you need initially is the interface information in the package specs. You can code and compile a spec without its body. Then, stored subprograms that reference the package can be compiled as well. You need not define the package bodies fully until you are ready to complete the application. Information Hiding: With packages, you can specify which types, items, and subprograms are public (visible and accessible) or private (hidden and inaccessible). For example, if a package contains four subprograms, three might be public and one private. The package hides the definition of the private subprogram so that only the package (not your application)

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 53: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 53/80

is affected if the definition changes. This simplifies maintenance and enhancement. Also, by hiding implementation details from users, you protect the integrity of the package. Added Functionality: Packaged public variables and cursors persist for the duration of a session. So, they can be shared by all subprograms that execute in the environment. Also, they allow you to maintain data across transactions without having to store it in the database. Better Performance: When you call a packaged subprogram for the first time, the whole package is loaded into memory. So, later calls to related subprograms in the package require no disk I/O. Also, packages stop cascading dependencies and thereby avoid unnecessary recompiling. For example, if you change the definition of a packaged function, Oracle need not recompile the calling subprograms because they do not depend on the package body.

Q94.What is the difference between sql and sql plus?Ans. The difference are given below.Sql plus SqlIt is interaction between System and user. It is interaction between user and database.It recognizes sql statement andsends them to the server

It is language that communicate with server..

Given by oracle corporation Based on ANSI standardKeyword can be abbreviated Keywords cannot be abbreviatedUse commands to manipulate the data Use function to manipulate the data

Q95.What is Web Database? Explain it in Detail.Ans.The Web and the Internet bring many new challenges to organizations. Today's Web sites are often a series of Web pages that take too much time and too many human resources to develop, deploy, and manage. In addition, their infrastructure may not be stable or robust enough to support mission-critical applications. Everything necessary to transform data into powerful Internet applications and content-driven Web sites is included with Oracle8i. It provides a Web development environment that allows software developers to easily build dynamic, data-driven Web sites with a standard Web browser and the Oracle8i database.WebDB is an HTML-based development tool for building HTML Web pages with content based on data stored in the Oracle database. Using a browser-based interface, Web pages can be created containing reports, charts, calendars, menus, and forms. WebDB provides build wizards for step-by-step guidance through the process of creating these components. The wizards include steps for building the PL/SQL statement that selects data used in the components, and steps for setting look and feel attributes of the component such as color and size.

Q96.What are methods for partitioning?Ans.Methods of partitioning:There are three methods of partitioning1. Range partitioning: - which partitions the data in a table or index according to a range of values2.Hash Partitioning: It partitions the data according to a hash function. 3. Composite Partitioning: It partitions the data by range and further subdivides the data into sub partitions using a hash function. Range partitioning was introduced in Oracle8 Hash and Composite portioning is new in oracle 8i.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 54: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 54/80

Logical and Physical attributes All partitions of a table or index have the same logical attributes, although their physical attributes may be different. For example, all partitions in a table share the same column and constraint definitions, and all partitions in an index share the same index columns, but storage specifications and other physical attributes such as PCTFREE, PCTUSED, INITRANS, and MAXTRANS may vary for different partitions of the same table or index.

Q97.What are rules for partitioning a table?Ans.The rules for partitioning tables are simpleA table can be range partitioned, provided that:1. It is not a part of a cluster.2. It does not contain LOB’s, LONG RAW data types.3. It is not an index-organized table. 4. If a table or index is partitioned on a column that has the DATE datatype and if the NLS date format does not specify the century with the year, the partition descriptions must use the TO_DATE function to specify the year completely; otherwise you cannot create the table or index.

Q98.Explain Range partitioning.Ans.Range partitioning maps rows to partitions based on ranges of column values. Range partitioning is defined by the partitioning specification for a table or indexThe partitioning specification for a table or index.PARTITION BY RANGE (column_list)The partitioning specifications for each individual partition:Values less than (value_list)Where: column_list is an ordered list of columns that determines the partition to which a row or an index entry belongs. These columns are called the partitioning columns. The values in the partitioning columns of a particular row constitute that row’s partitioning key.Value_list is an ordered list of values for the columns in column_list.Partition NamesEvery partition has a name, Partition name must confirm to usual rules for naming schema objects and their parts. Name of a table partition must be unique among all partitions belonging to the same parent table.Name of on index partition must be unique among all partitions belongings to the same parent index.A partition can be renamed, but it is not possible to create a synonym on a partition name.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 55: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 55/80

Section – C 10 Marks Questions[QUESTIONS 1 TO 20] [PAGE 55 TO 80]

Q1. What is data base management system .explain its advantages and disadvantages?Ans.Database Management System (DBMS): A data base management system is a software that enable users to create and maintain database. For example every individual or a company has a data, which is to be stored and manipulated. i.e. adding new data, deleted unwanted data or making changes in the existing data. The DBMS is thus a general-purpose system that facilities the process of defining, constructing and manipulation database for various applications.Defining a database involves specifying the types of data to be stored in the database, along with its description.Constructing the database is the process of storing the data itself on some storage medium, which is controlled by the DBMS.Manipulating the database includes functions like querying the database to retrieve specific data, updating the data to reflect changes and generating reports from the data.Advantages of DBMSReduction of redundancies: Centralized control of data by the DBA avoids unnecessary duplication of data and effectively reduces the total amount of data storage as required.Shared data: A database allows the sharing of data under its control by any number of application programs or user.Integrity: Centralized control can also ensure that checks are incorporated in the DBMS to provide data integrity. Data integrity means data value being entered for storage could be checked to ensure that they fall within a specified range and are in correct format.Security : Data is vital important to an organization and should be accessed by unauthorized person. Data independence: Data independence is are considered from two points of view:Logical Level: This level of abstraction describes what data is stored in the database, and what relationships exist among them.Physical Level: This is lowest level of abstraction and describes how the data is actually stored. At the physical level complex low-level data structures are described in detail.Controlling the data redundancy Duplication of same data in different files Wastage of storage space, since duplicated data is stored. Time in entering data again and again is wasted.Elimination of Inconsistency In the file processing system information is duplicated throughout the system. So changes made in one file may be necessary be carried over to another file.

Disadvantages of DBMS: A significant disadvantage of DBMS system is the cost. In addition to the costs of purchasing or developed the software, the hardware was to be upgraded to allow for the extensive programs and the workspaces required for the execution and storage. An additional cost is that of migrant from a traditionally separate application environment to an integrated one. While centralization reduces duplication, the lack of duplication requires that the database be adequately backed up so that in the case of failure the data can be recovered. Backup and

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 56: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 56/80

recovery operations are fairly complex in DBMS environment, and become worse in a multi-user database system.

Q2. Explain the file management system along with its disadvantages. And architecture of dbms?Ans.File Management System: The file management system was the first method used to store data in computerized database. The data item is stored in one large file. A particular relationship cannot be drawn between the items other than the sequence in which it is stored. If a data item has to be located, the search start at the beginning and item are checked sequentially till the required item is foundDisadvantage of File management system1. Locating and retrieving a record is very tedious process because of its sequential access method.2. Altering the file has to be read and rewritten. It involves writing the new data item into a temporary file, adding this item as a last field each record deleting the original file and renaming the temporary file Architecture of DBMS:

4. INTERNAL LAYER OR NATIVE LAYER: The internal view is the view about the actual Physical storage of data. It tells us how data is stored physically in the database. It also tells the physically implementation of the database to achieve optimal runtime performance and storage space utilization. 5. CONCEPTUAL OR PHYSICAL LAYER: The conceptual view describes the structure of the whole database for a community of users. The conceptual view represents all the database entities, their relationships, information on data, constraints on data, security and integrity information etc. 6. EXTERNAL OR LOGICAL LAYER: This external level includes a number of user views, which describe the part of the database that is a particular user group is interested in and hides the rest of the database from the user group.

Q3. What is normalization ? Write about the various rules to apply normalization on the database . Explain various normal forms, Write its advantages.Ans. Normalization: Normalization is widely used in relational database. It is the process of splitting the relations into relations with fewer attributes by minimizing the redundancy of data and minimizing insertion, deletion and updating anomalies. Normalization may be defined as

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

External level

Conceptual level

Internal level

Hardware

End user

End useEnd user

Page 57: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 57/80

a step-by-step reversible process of transforming an unnormalized relation into relations with progressively simpler structures. Normalization is based on the concept of normal forms. Normalization rules:There are a few rules that can help you achieve a sound database design: 1) A table should have an identifier. The fundamental rule of database design theory is that each table should have a unique row identifier, a column or set of columns that can be used to distinguish any single record from every other record in the table. Each table should have an ID column, and no two records can share the same ID value. The column or columns serving as the unique row identifier for a table are the primary key of the table. 2) A table should store only data for a single type of entity. Attempting to store too much information in a table can prevent the efficient and reliable management of the table’s data. 3) A table should avoid null able columns. Tables can have columns defined to allow null values. A null value indicates that there is no value. While it can be useful to allow null values in isolated cases, If you have a table with several null able columns and several of the rows have null values in the columns. 4) A table should not have repeating values or columns. The table for an item in the database should not contain a list of values for a specific piece of information. If you find that you need to store a list of values in a single column, or if you have multiple columns for a single piece of data (au_lname1, au_lname2, and so on), you should consider placing the duplicated data in another table with a link back to the primary table. various normal forms, their anomalies and advantages.The normal forms of normalizations are as follows:First Normal Form: If the values in the relation instances are atomic for every attribute in the relation, the relation is said to be in the first Normal form. Any relation is called atomic if the element of the relation is indivisible. I.e. cannot be broken down further. Anomalies of first normal form:1. Repetition of information2. Inability to represent certain informationSecond Normal Form: If every non-key attribute of a relation schema is fully functionally dependent on the key then relation is said to be in 2nd NF. 2nd NF is also in 1NF.Those relation are not in 2NF can be converted into 2NF using the following procedure.For each functional dependency, which is not fully functionally dependent on the key, form new relations using its attributes.The attributes on the right hand side of the above FDs are eliminated from the original relation.Advantages:Redundancy, which was pointed out the 1NF, does not exist in 2NF.Certain information can also be retrievedAnomalies: Transitive Dependency is a Functional dependency XY in a relation scheme R is a transitive dependency if there is a set of attributes Z that is neither a candidate key nor a subset key of R and both XZ and Z—Y holds. A general case of transitive dependency is as follows:A, B, C are three columns in a tableIf C is related to BIf B is related to A Then C is related to A..

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 58: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 58/80

Third Normal Form: A relation is set to be 3nf if it is in 2nf and the no known key attribute of the relation is transitively dependent on the primary key. In 3nf the 2nf relation are converted into the smaller relations such that no relation contains any transitive dependency involving key attributes.Anomalies:It may contain redundancy of data.

Q4. Explain Entity Relationship model and What is E-R Diagram? What are its Various Components?Ans.Entity Relationship Model: Entity set is represented by E-R relationship and is mapping from one entity set to another. The E-R model is usually shown on pictorially using entity relationship diagram. The entities and the relationship between them are shown using the following convention: - An entity is shown as rectangle A diamond represents the relationship among a number of entities, which are connected to the diamond by lines. The attribute shown as ovals are connected to the entities relation by lines. Diamond, ovals and rectangle are labeled the type of relationship existing between the entities is represented by giving the cardinality of the relationship on the joining the relationship to the entities.Entity Relationship Diagram: Entity set is represented by E-R relationship and is mapping from one entity set to another. The E-R model is usually shown on pictorially using entity relationship diagram.The Pictorial representation is as follows:

Rectangle Diamond

Oval LineCreating an entity relationship diagram1. Identify the entities.2. Define the identifiers.3. Define the relationships4. Determine cardinality of the relationship.5. Determine descriptive attributes.6. Create the ER-diagram.7. Review and refine the record.

The Entity-Relationship(E-R) diagram represents the logical structure of a database by using entities and relationships between the entities. You can graphically represent an E-R model by using Entity-Relationship[(ERD) diagram.The entity-relationship model is based on a perception of the world as consisting of a collection of basic objects (entities) and relationships among these objects. An entity is a distinguishable object that exists. Each entity has associated with it a set of attributes describing it. E.g. number and balance for an account entity. A relationship is an association among several entities. e.g. A cust_acct relationship associates a customer with each account he or she has. The set of all entities or relationships of the same type is called the entity set or relationship set.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 59: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 59/80

Cardinality:It is simply the no of tuples (rows )in a relation(table)Cardinality is very important database properties. Cardinality is a relationship property that indicates the number of related instances an entity may have. An entity may have zero, one, or many related entity instance.Another essential element of the E-R diagram is the mapping cardinalities, which express the number of entities to which another entity can be associated via a relationship set. An E-R diagram can express the overall logical structure of a database graphically: Rectangles: represent entity sets. Ellipses: represent attributes. Diamonds: represent relationships among entity sets. Lines: link attributes to entity sets and entity sets to relationships. The E-R model is beneficial for a database Designer in various ways, which are:The constructs used in the E-R model can easily be transformed into relational tables.Simple and easy to understand and is, therefore used by a database designer to communicate a database design to the user accessing the database.Is used as a design plan by a database developer to implement a data model is database management system.

Q5. What are SQL operators?Ans.In relational algebra-Selection operator: The selection operator on a given relation r produces a new relation that has the same attributes of r and whose rows are these rows of r that satisfy a specified condition.Projection operator: The projection operator, when applied to a relation r and a set x of its attributes, produces a new relation where there are no duplicate rows and whose attributes are the elements of x. This operator is implemented in SQL using the distinct option of the select clause of the select command.Join operator: The join operation allows us to bring data from two or more tables together into a single table. The tables that participate in the join are “connected” through their common attributes according to the condition specified in the where clause.SQL supports a number of other operators, to perform operations on data stored in the table.Operators are broadly classified as:ArithmeticComparisonLogicalARITHMETIC OPERATORS:- SQL supports the basic arithmetic operators: Addition, Subtraction, Multiplication and Division. Arithmetic operations are generally performed on the column values of the table, with a SELECT clause. Table below lists the arithmetic operators, supported by SQL:Symbol Description+ Addition- Subtraction* Multiplication/ DivisionFor example in the fare table to hike(increase) the fare of all the flights by 10% the SQL statement would be:SELECT flight_route_id ID, class, fare, fare + 0.1 * fare "NEW FARE" FROM fare;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 60: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 60/80

In the above example SELECT statement selects the flight_route_id and aliases the column name to ID, travel class, original fare and new fare after 10% hike.COMPARISON OPERATORS :- Comparison operators are generally used to compare two values and specify the condition. Table below lists the comparison operators supported by SQL and their symbols.Symbol Description

Example= Equal to A=B, where A=5 and B=5< Less than A<B, where B=7 and A=0, 1, 2….6> Greater than A>B, where A=7 and B= 0, 1, 2….6<= Less than or equal to A<=B, where B=7 and A=0, 1, 2….7>= Greater than or equal to A>=B, where A=7 and B= 0, 1, 2….7!= Not equal to A!= B, where A=3, B=1<> Not equal to A<>B, where A=3,B=1LIKE Pattern matching A like B, where A=’TATA’, B=’TATA’NULL Is equal to null A is NULL, where A has no valueNOT NULL Is not equal to null A is NOT NULL, where A must have someLOGICAL OPERATORS :The AND operator: The AND operator retrieves only those rows whose satisfy the both conditions.

Select column list from table name where condition1 and condition 2The OR operator: The OR operator retrieves only those rows that satisfy either or both

conditions. The syntax of using OR with two Boolean conditions looks like this.Select column list from table name where condition /OR condition2The NOT operator: The NOT operator is used to specify the columns values that are used to exclude the record from display. The NOT acts only on one condition. It is a unary operator. The syntax for using NOT with a where condition looks like:Select ename, deptno from emp where deptno Not in (select deptno from emp where ename=’Pardeep’This display the records of all the employees who does not work in Mr. Pardeep’s Department.PATTERN SEARCHING-LIKE Operator-

LIKE performs pattern matching. An underline (_) represents one space. A percent sign (%) represents any number of spaces or characters. For example Features like ‘Mo%’ Begins with letter Mo and Feature like ‘_I%’.RANGE SEARCHING-Between Operator-this select all the rows from the table which are in between the specified range.

Q6. What are commonly built in DataTypes available in Oracle? Explain Advantages and Disadvantages of relational model.Ans.Data Types are very important in Oracle Oracle treats values of one datatype differently from values of another dataype. Oracle provides a number of built-in datatypes as well as user defined datatypes. Here we are taking some simple built-in datatypes, user defined datatypes.

Commonly used built in DataTypes in Oracle are:

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 61: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 61/80

CHAR (size): It stores character or alphanumeric data, where maximum number of characters stored is equal to the number of bytes defined by size. When a table is created with CHAR datatype column, for every data value entered in that column Oracle reserves the number of bytes equal to number of bytes defined by size in the memory. VARCHAR2 (size): Similar to CHAR datatype, VARCHAR2 is also used for storing the alphanumeric data, where maximum length is equal to the number of bytes specified by size.Default value for a VARCHAR2 column is zero character and the maximum allowed is 4000 bytes. It is must to specify the maximum length for a VARCHAR2 column. This maximum must be at least 1 byte. NUMBER(p,s) It can store a number with precision p and scale s. This means that it can store a number having maximum number of digits after decimal point equal to s and before decimal point equal to p. A Number datatype can store zero, positive, and negative fixed and floating-point numbers with 38 digits of precision and range of scale from –84 to 127. LONG datatype column is capable of storing a variable-length character string containing up to 2 gigabytes, or 2 31 -1 bytes. For memory reservation LONG column have the characteristics similar to VARCHAR2 column. The length of LONG values may be limited by the memory available on your computer. A table can’t contain more than one long data type column. Thus as far as possible, use of long datatype columns should be avoided. DATE: DATE data type stores the date and time information, in the format: century, year, month, day, hour, minute, and second. Default value for time is 12:00:00 AM (midnight) and default value for date is first day of current month. SYSDATE is a date datatype, gives the current date and time. SYSDATE + 1 will give the date of tomorrow. RAW (SIZE), LONG RAW this is used to store the binary data, where data is not to be interpreted by Oracle. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of binary data, for which the interpretation is dependent on the use. Like Long datatype Long Raw datatype imposes a lot of restrictions, so as far as possible its use should be avoided. ROWID is a pseudocolumn that stores the address of each row of table in the database. Datatype ROWID stores a hexadecimal string representing the address of row.

Advantages of Relational Model6. Simplicity: The relational database model is very simple and easy to design and implement at the logical level. All the relations are designed in a tabular manner, which helps the user to concentrate on the logical view of the database.7. Flexible: The relational database provides flexibility that allows changes to database structure easily.8. Data Independence: The structure of database can be changed without having to change any applications that were based on that structure.9. Structural Independence: relational database is only concerned with data and not with the structures, which improves performance.10. Query Capability: In this model the queries are based on logical relationships and processing those queries does not require predefined access paths among the data i.e. pointers.Disadvantages5. It provides the limited ability to deal with images spread sheets etc.6. This model is very costly because it requires latest hardware technology.7. Mapping objects to relational database can be difficult skill to learn 8. Relational model is not suitable for huge databases but suitable for small databases.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 62: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 62/80

Q7. Explain the duties of DBA AND What is a relationship? How many types of relationships are in RDBMS?Ans.Data base administrator is the person who makes the strategic and policy decisions regarding the data of the enterprise. DBA is the person who provides the necessary technical support for implementing those decisions. Thus DBA is responsible for the overall control of the system at technical level.6. Defining the conceptual schema: It is the job of DBA to decide exactly what information is to be held in the database. In other words, to identify the entities of interest to the enterprise and to identify the information to be recorded about these entities.7. Defining the internal schema: The DBA must also decide how the data is to be represented in the stored database. In addition he must also define mapping between the internal and conceptual schema.8. Liaising (communication) with users: It is the business of DBA to liaise with users, to ensure that data they require is available and to write the necessary external schema. 9. Defining security and integrity rules: Security and integrity rules can be regarded as part of the conceptual schema. The conceptual DDL should include facilities for specifying such rules.10. Defining backup and recovery procedures: Once the database is designed, whole working of enterprise is dependent on it. So it becomes important to take regular backups of database. In the event of damage the data can be recovered from the most recent backup.Relationship AND types of relationships are in RDBMS ARE GIVEN BELOW.Relationship among Data: - A relational ship is defined as “an association among entities”. A relationship type is an association of entity types, while a relationship instance is an association of entity instance is an association of entity instances. A relationship may associate an entity with itself. The three different types of relationship may recognized among various data stored in the database are;ONE TO ONE: - Consider an example a set of students in a class. Each student can have only one roll no. Similarly each roll number can be associated only with one student. This is the case of a one to one relationship.

Many to One: - One student can register for only one particular course at a time. Where as a number of students could register for the same course. This can be illustrated with the following figure;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

AssignedStudent1 Rollno-1

Register Course

Student 1

Student 2

Student 3

Page 63: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 63/80

Many to Many: - A vendor can sell a number of items and many vendors can sell a particular item. The following Figure will clear it to you.

Q8. Write down the features of Oracle 8i. AND What is operator define the is operator, in and between operator?Ans.Oracle8i Enterprise edition adds several high-end features and options for mission-critical OLTP and data warehousing applications, apart from the usual features of standard edition of Oracle8i. Oracle8i Enterprise Edition for Windows NT is a development and deployment platform for the Internet. Oracle8i Enterprise Edition for Windows NT features include the following:g) A built-in Java Virtual Machine that lets you store and run Java code within an Oracle database. The Java VM provides a runtime environment for Java objects. It fully supports Java data structures, method dispatch, exception handling, language-level threads, and the entire core Java class libraries.h) Support for the Common Object Request Broker Architecture (CORBA), the Internet Inter-ORB (Object Request Broker) Protocol (IIOP), and Enterprise Java Beans. CORBA objects communicate using OMGs Internet Inter-ORB Protocol (IIOP), the standard for communication between and among distributed objects running on the Internet, intranets, and in enterprise computing environments. Oracle8i integrates a Java-based CORBA 2.0 compliant Object Request Broker (ORB) that provides users with the ability to call into and out of the database server using CORBA's IIOP. i) Support for SQLJ, a programming syntax that lets you embed SQL statements in Java programs.j) Integration with the Component Object Model (COM) and Microsoft Transaction Server. k) Component software has recently been promoted as the next evolution in software development. The growth of object-oriented programming and distributed objects are proof of this industry-wide trend. l) The scripting of components enables you to reuse code that is pre-built and pre-tested. The reuse of code fulfills one of the key objectives of software development: shorter development cycles and reduced time to market. g) Oracle COM Automation feature has been created to enable you to use COM-based components to customize and enhance the functionality of the Oracle8i database on Windows NT.is operator, in and between operator

There are different types of operators in sql. All operators are used with the where clause. Operators are used to execute the potential record’s Column value against a specified value. If evaluation is true then it display the records.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Vendor 1

Vendor 2 Vendor 4

Vendor 3

Page 64: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 64/80

IS Operator- The equal (=) operator is used to compare the value with another values of the tables. This operator cannot be used if the argument is null in that case we use IS operator in place of the (=) equal operator. The is operator is used with null argument.Lets take an example of this:-Sql> Select EMPID, ENAME,WAGES from employeeWhere name=’SHAM’ || wages IS NULL;OutputEMPID ENAMEWAGES1 Deepak2 Sham 120003 Ram 100004 RohitIN operator- The IN operator is used to retrieve the value from the column of the table those values are define in the query.ExampleSql> Select empid, Ename from employee where ename IN( ‘Sham’,’Ram’);OutputEMPID ENAME2 SHAM4 RAM

Between operator - It compare the column value with two arguments. If the value is within a range of the arguments then condition is true. If the value equals either high or low range the condition is also true. The condition is false if value is outside the range.This operator consist of two keywords.First is BetweenSecond is ANDExampleSql> Select Ename,wages from employee where wages between 10000 AND 15000;Output Ename wagesSham 12000Ram 10000

Q9. Explain SQL Functions in Details.(important)Ans:Oracle implicitly converts the argument to the expected data type before performing the SQL function. If a SQL function is called with a null argument, the SQL function automatically returns null. The only SQL functions that do not follow this rule are CONCAT, DECODE, DUMP, NVL, and REPLACE.Types of functionsCharacter functionsNumber functionsDate functionsConversion and Transformation functions1. CHARACTER FUNCTIONS: These functions take a character string as an argument. There are two types of character functions:(a) Character functions returning character values. Some of the important character functions that return character values are as follows:

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 65: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 65/80

RPAD, LPAD, LTRIM, RTRIM, LOWER, UPPER, INITCAP(b) Character functions returning numeric values. Some of the most commonly used functions in this category are:INSTR, LENGTHNUMBER FUNCTIONS: Number functions accept numeric input and return numeric values. Most of these functions return values that are accurate to 38 decimal digits. These are mainly of two types:Single row functionsAggregate functions1 Single row functionsThese functions return a single result row for every row of a queried table or view.S. No.

Function Name

Syntax Description

1. ABS ABS(VALUE) It returns the absolute value. For example ABS(-3.456) would return 3.456.

2. CEIL CEIL(VALUE) It produces a whole number that is greater than or equal to a specified value. For example CEIL (99.56) and CEIL (-12.23) would return 100, -12 respectively.

3. POWER POWER (VALUE, EXPONENT)

Raises a value to a given positive exponent. Ex: POWER (4, 2) would return 16.

4. EXP EXP (VALUE) Exponential e(2.71828183) raised to specified power. Ex: exp (3) would return

5. LN LN (value) Natural or base e logarithm of a value LN (3) would return 1.098612

6. LOG LOG (base, value) It returns the logarithm of value at a given base value. Ex: LOG (10, 100) would return 2.

7. ROUND ROUND (value,Precision)

Rounds off value to a given number of digits of precision. Ex: ROUND (22.345,1) would return 22.3

8. NVL NVL(value, substitute)

If value is NULL, function returns Substitute, otherwise it returns the value.

Aggregate functionsAggregate functions return a single row based on groups of rows, rather than on single row.S. No. FUNCTION Description1. AVG It calculates the average of a column in database. It doesn’t consider

NULL values while calculating the average.2. COUNT It counts the number of rows in the column having NOT NULL values.

If count (*) is used then it counts NULL values too.3. SUM Adds up values in column4. MAX MAX Gives the max value in a column5. MIN MIN Gives the min. value in a column

2. DATE FUNCTIONS: Date functions operate on values of the DATE datatype. All date functions return a value of DATE datatype, except the MONTHS_BETWEEN function, which returns a number. Some of the important date functions are as follows:3. ADD_MONTHS, LAST_DAY, MONTHS_BETWEEN, NEW_TIME, NEXT_DAY, ROUND, TRUNC, TO_DATE, TO_CHAR

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 66: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 66/80

4. CONVERSION AND TRANSFORMATION FUNCTIONS: These functions are used for substitution of a column value by some other value. Functions used for this purpose are TRANSLATE and DECODE. 5. TRANSLATE: - It does an orderly character-by-character substitution in a string; the syntax for this function is as follows:TRANSLATE (string, if, then)SELECT passenger_id id,name, TRANSLATE (cc_no,'0123456789',' xxxxxxxxxx') “credit_card_no" FROM passengers_detail;1 DECODE:-It does a value-by-value substitution. For every value it sees in a field, DECODE checks for a match in a series of if/then tests, the syntax for this function is as follows: DECODE(value, if1,then1,if2,then2......,default)

Q10.Explain the architecture of the PL/SQL in Detail. Also explain Character set of PL/SQL Explain it in Detail and also Explain Structure of PL/SQL?Ans.PL/SQL Stands for Procedural Language/SQL. PL/SQL is a development tool that extends the features provided in the SQL database language. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks.Allows using general programming tools with SQL, for example: loops, conditions, functions, etc.This allows a lot more freedom than general SQL, and is lighter-weight than JDBC (Java Database Connectivity) is used to connect Java programs with databases.PL/SQL BLOCKPL/SQL code is built of Blocks, with a unique structure.There are two types of blocks in PL/SQL:1. Anonymous Blocks: have no name (like scripts). can be written and executed immediately in SQLPLUS can be used in a trigger.2. Named Blocks: Procedures Functions Anonymous Block Structure:DECLARE (optional)/* Here you declare the variables you will use in this block */BEGIN (mandatory)/* Here you define the executable statements (what the block DOES!)*/EXCEPTION (optional)/* Here you define the actions that take place if an exception is thrown during the run of this block */END; (mandatory) /CHARACTER SET OF PL/SQL: When we write a PL/SQL program as lines of text using a specific set of characters. The PL/SQL character set includes.The upper and Lowercase Letters A….Z, a…..zThe number 0…9Tabs, spaces, and carriage returnsThe symbol is not case sensitive, so lowercase letters are equivalent to corresponding uppercase letters except within string and character literals.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 67: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 67/80

Structure of PL/SQL: PL/SQL is a 4GL (fourth generation) programming language. It offers all features of advanced programming language such as portability, security, data encapsulation, information hiding etc. A PL/SQL program may consists of more than one SQL statements, while execution of a PL/SQL program makes only one call to Oracle engine, thus it helps in reducing the network overheads.Structure of PL/SQL: PL/SQL is a block structure language. This means a PL/SQL program is made up of blocks, where block is a smallest piece of PL/SQL code having logically related statements and declarations. A block consists of three sections namely: Declare Begin and Exception followed by an End statement. Declare sectionDeclare section declares the variables, constants, processes, functions etc., to be used in the other parts of program. It is an optional section.Begin sectionIt is the executable section. It consists of a set of SQL and PL/SQL statements, which is executed when PL/SQL block runs. It is compulsory section.Exception SectionThis section handles the errors, which occurs during execution of the PL/SQL block. This section allows the user to define his/her own error messages. This section executes only when an error occurs. It is an optional section.End Section

This section indicates the end of PL/SQL block.

Q11.Explain Different data types available in PL/SQL. AND What are features of PL/SQL?Ans.Every constant and variable has a datatype. A datatype specifies the space to be reserved in the memory, type of operations that can be performed and valid range of values. PL/SQL supports all the built in SQL datatypes. PL/SQL provides some other datatypes. Some commonly used PL/SQL datatypes are as follows:BOOLEAN:- One of the mostly used datatype is BOOLEAN. A BOOLEAN datatype is assigned to those variables, which are required for logical operations. A BOOLEAN datatype variable can store only logical values, i.e. TRUE, FALSE or NULL. %TYPE: -The %TYPE attribute provides the datatype of a variable or database column. In the following example, %TYPE provides the datatype of a variable:balance NUMBER(8,2);minimum_balance balance%TYPE;In the above example PL/SQL will treat the minimum_balance of the same datatype The %TYPE attribute is particularly useful when declaring variables that refer to database columns.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 68: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 68/80

%ROWTYPE :- The %ROWTYPE attribute provides a record type that represents a row in a table (or view). The record can store an entire row of data selected from the table. In the example below emp_rec is declared as a record datatype of emp table. emp_rec can store a row selected from the emp table.emp_rec emp%ROWTYPE;features of PL/SQL

PL/SQL is completely portable, high-performance transaction processing language that offers the following advantages: Support for SQL: SQL has become the standard database language because it is flexible, powerful, and easy to learn. SQL is a non-procedural meaning that you can state what you want to do without stating how to do it. A few English-like commands such as Insert, Update and Delete make it easy to manipulate the data stored in a relational database. Support for Object Oriented Programming: Object types are an ideal object-oriented modeling tool, which you can use to reduce the cost and time required to build complex applications. Better Performance: PL/SQL also improve performance by adding procedural processing power to Oracle tools. Using PL/SQL a tool can do any computation quickly and efficiently without calling on the oracle server. This saves time and reduces environments. Higher Productivity: PL/SQL adds functionality to non-procedural tools such as oracle forms and Oracle reports. With PL/SQL in these tools, you can use familiar procedural constructs to build applications. Integration with Oracle: Both PL/SQL and Oracle are based on SQL. PL/SQL supports all the SQL data types. The %TYPE and %ROWTYPE attributes further integration PL/SQL with the data dictionary.Q12.Explain Procedure , Function AND CURSOR in Details. Also explain CURSOR’S their attributes.Ans.A procedure is a subprogram that performs some specific task, and stored in the data dictionary. A procedure must have a name so that it can be invoked or called by any PL/SQL program that appears within an application. Procedures can take parameters from the calling program and perform the specific task. When a procedure is created, the Oracle automatically performs the following stepsThe syntax for creating a procedure is follows:CREATE OR REPLACE PROCEDURE [schema.] procedurename [(argument {IN, OUT, IN OUT} data type …)] {IS, AS}[Local variable declarations]BEGINExecutable statementsEXCEPTIONException handlersEND [procedurename];1. Compiles the procedure2. Stores the procedure in the data dictionaryThe oracle compiles the PL/SQL block. If an error occurs during creation of procedure, Oracle displays a message that procedure is created with compilation errors, but it doesn’t display the errors. To see the errors following statement is used.SELECT * FROM user_errorsFUNCTION: - Function is similar to procedure except that it must return one and only one value to the calling program.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 69: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 69/80

The syntax for function is as follows:CREATE OR REPLACE FUNCTION [schema.] functionname [(argument INdatatype, ….)] RETURN datatype {IS,AS}[local variable declarations];BEGINExecutable statements;EXCEPTIONexception handlers;END [functionname];Cursor AND their attributes: A cursor is a private area for SQL operations, used by the Oracle engine. This is an area in the memory in which a parsed statement and other information for processing the statements are kept. Oracle uses work areas to execute SQL statements and store processing information. A cursor is a PL/SQL construct. It allows naming a work area and accessing its stored information. In oracle cursor is used for easy processing to handle multiple record queries. Cursors are constructs that enable the user to name a private memory area to hold a specific statement for access at a later time.Attributes of Cursor: Implicit cursors have certain attributes that can be used to access information about the most recently executed SQL statement using cursor. The implicit cursor attributes are as follows:%ISOPEN%NOTFOUND%FOUND%ROWCOUNT%ISOPEN: -This attribute always returns false for implicit cursor, because Oracle automatically closes the implicit SQL cursor after executing its associated SQL statement.%NOTFOUND : -The %NOTFOUND attribute returns true if DML statement like INSERT, UPDATE and DELETE affects no rows and do not have a return value, else it evaluates to false. It is used to determine that no rows are processed in an SQL statement. %FOUND: - The %FOUND attribute is just the logical reverse of %NOTFOUND attribute. This attribute also returns Boolean variable. It evaluates to true if DML statements like INSERT, UPDATE and DELETE affects one or more rows or SELECT returns one row. %ROWCOUNT: - The %ROWCOUNT is used to determine the no of rows that are processed by the DML statement. It returns the number of rows affected by INSERT, UPDATE and DELETE statement or returned by a SELECT INTO statement. It returns zero if the SQL statement affects or returns no rows.

Q13.What are Advanced Data Types? Also explain following data types in detail.1) Internal LOB2) External LOB3 CREATING USERCHANGING PASSWORD WITH EXAMPLES?Ans.There is another category of data types available in Oracle called Large Objects or LOBs. As the name suggests, these data types can store large amount of data. These advanced data types can store unstructured information such as sound clips, video files up to 4 gigabytes in size. They allow efficient, random, piece-wise access to data. The LOB types store values, which are known as locators. These locators store the location of large objects. LOB values can be operated upon through the use of locators.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 70: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 70/80

Types of LOBOracle8 regards LOBs are defined into two types internal LOBs and external LOBs, also referred to as BFILEs (binary files).

a. INTERNAL LOB: Internal LOBs, as their name suggests, are stored inside database table spaces in a way that optimizes space and provides efficient access. You can recover internal LOBs in the event of transaction or media failure, and any changes to an internal LOB value can be committed or rolled back. Internal LOB Data typesThere are three SQL data types for defining instances of internal LOBs:BLOB: - A LOB whose value is composed of unstructured binary data up to 4GB in length, stored in database.CLOB: - A LOB whose value is composed of character data up to 4GB in length, stored in database.NCLOB: - A CLOB column that supports a multi byte character set.External LOB: -External LOBs are also known as BFILES. They are large binary data objects stored in operating system files outside the database table spaces. BFILEs are located on tertiary block storage devices such as CD-ROM, PhotoCDs and DVDs. External LOB does not participate in transactions. Any support for integrity and durability must be provided by the underlying file system as governed by the operating system.External LOB Data typeThere is one external SQL LOB data type:BFILE A LOB whose value is composed of binary ("raw") data, and is stored outside the database table spaces in a server-side operating system file. CREATING USER: - New user in Oracle can be created using either Enterprise Manager or SQL *DBA or the SQL command CREATE USER. The syntax for creating user is as shown below. CREATE USER USERNAMEIDENTIFIED [BY PASSWORD | EXTERNALLY |GLOBALLY AS ‘EXTERNAL_NAME’][DEFAULT TABLESPACE TABLESPACE ][TEMPORARY TABLESPACE TABLESPACE ][QUOTA { N [ K | M ] UNLIMITED } ON TABLESPACE ][PROFILE PROFILE ][ACCOUNT [LOCK | UNLOCK ][PASSWORD EXPIREA new User must have a name and a method of identification. The other parameters all have default values. The name is used as login, while the password is for user authentication. For example, a user can be created as follows:SQL > CREATE USER VMC IDENTIFIED BY 12345;CHANGING PASSWORD:- Password can be easily altered by the DBA (Database Administrator) or through the security manager. This can be done in SQL using the command ALTER USER. The exact syntax is as follows:SQL > ALTER USER USERNAME IDENTIFIED BY NEWPASSWORDFor example, the password for the user VMC can be changed to ‘abc123’ as follows:SQL > ALTER USER VMC IDENTIFIED BY abs123;

Q14.Explain the types of LOCKS.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 71: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 71/80

Ans.Locks are mechanism used to prevent destructive interaction between users accessing the same resource simultaneously. A resource can either be an entire table or a specific row in a table. Thus a lock provides a high degree of concurrency. Locks can be acquired at two different levels.1 Row Level Locks2 Table level LocksROW LEVEL LOCKS: In the row level locks arrow is locked exclusively so that the other users cannot modify the row until the transaction holding the lock is committed or rolled back. Rowlocks are acquired automatically by oracle as a result of Insert, Update, Delete and Select…for update clause statement. For example a user in marketing division needs to update row in the order_master table. A lock applied to prevent other users from manipulating the row till the update is completed. The lock can be given with the following Select statement.

SQL > Select * from order_master where code=-‘v002’ update of odate, deldate;The following update command corresponds to the above example.SQL > Update order_master set del_date=’31-jan-99’ where code=v002’;In the above example the record is updated where code=’v002’ for marketing division. Since the rows are locked by the ‘for update’ clause no other user in the acc department can update that particular row till the lock is released.TABLE LEVEL LOCK: -A table level lock will protect data thereby guaranteeing data integrity when multiple users are accessing data concurrently. A table lock can be held in several modes. They are;1 Share Lock2 Share Update Lock3 Exclusive LockThe general syntax for locking a table is given below.LOCK Table<Table_name> in <share or share update or exclusive mode>;Table Levels Modes are explained below.SHARE LOCK: Locks the table allowing other user to only query but not insert, update or delete rows in the table. Multiple users can place share locks on the same table at the same time.

Syntax is;SQL > LOCK TABLE ORDER_MASTER IN SHARE MODE;

SHARE UPDATE LOCK: It locks rows that are updated in a table. It permits other users to concurrently query, insert, update or even lock other rows in the same table. It prevents the other users from updating the row that has been locked.

Syntax is;SQL > LOCK TABLE EMP IN SHARE UPDATE MODE;

EXCLUSIVE MODE: -This is the most restrictive of table locks. When one user issues it, it allows the other users to only query but not insert, update, delete or update rows in a table.

Syntax is;SQL > LOCK TABLE EMP IN EXCULISIVE MODE;

Note: Locks can be released by issuing either ROLLBACK or COMMIT command.

Q15.What are Triggers? What are various forms of Database Triggers? Explain with example.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 72: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 72/80

Ans.Triggers: Data base triggers are procedures that are stored in the database and are implicitly executed (fired) when the contents of a table are changed.A trigger can permit DML statements against a table only if they are issued, during regular business hours or on predetermined weekdays.These database objects consist of the following sections.1 A named database event and2 A PL/SQL block that will when the event occurs.USES OF DATABASE TRIGGERS:1 A trigger can permit DML statements against a table only if they are issued, during regular business hours or on predetermined weekdays.2 A trigger can also be used to keep an audit trail of a table along with the operation performed and the time on which the operation was performed. It can be used to prevent invalid transactions. Enforce complex security authorizations.Types of Triggers1. Row Triggers2. Statement Triggers3. Before Triggers4. After TriggersRow Triggers: A row trigger is fired each time the table is affected by the triggering statement. For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement.

Statement Triggers: Statement triggers are useful if the code in the trigger action does not depend on the data provided by the triggering or the rows affected.

Before vs. After triggers :When defining a trigger you can specify the trigger timing, i.e. you can specify when the triggering action is to be executed in relation to the triggering statement. BEFORE and AFTER apply to both row and statement triggers. BEFORE TRIGGERS:Before triggers execute the trigger action before triggering statement. AFTER TRIGGERS:After trigger executes the trigger action after the triggering statement is executed.ExampleCREATE OR REPLACE TRIGGER con_upper BEFORE INSERT ON client_master FOR EACH ROWBEGIN: NEW.CLIENT_NAME:=UPPER (:NEW.CLIENT_NAME);Stored Procedures- Procedures are named PL/SQL blocks that can take parameters, perform an action and can be invoked. A procedure is generally used to perform an action and to pass values.Procedures are made up of:

1. A declarative part,2. An executable part, and3. An optional exception-handling part.

When a procedure is created, ORACLE automatically performs the following steps:

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 73: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 73/80

1. Compiles the procedure.2. Stores the compiled code.3. Stores the procedure in the database.ExampleCREATE PROCEDURE MyProc (ENO NUMBER) AS BEGIN DELETE FROM EMP WHERE EMPNO= ENO; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(‘No employee with this number’); END;

Q16.Explain exception handling.Ans. The exception section is an optional section of PL/SQL program that tells PL/SQL how to handle particular exceptions. Whenever an error is encountered in the executable section it exits the executable section and searches the section for the exception matching the error. If it is found it will execute the code handled by the exception. The exception section is the last section of the PL/SQL block and is also known as error handling section.

Types of ExceptionsExceptions can be classified into two types

Predefined Exceptions User DefinedPredefined Exceptions: PL/SQl provides a predefined set of exceptions that are implicitly raised by the system internally at run time, in case an error is encountered in PL/SQL. Whenever oracle encounters system errors at run time, the corresponding predefined exception is implicitly raised and as a result normal execution stops and control is transferred the specified exception handler. For example TOO_MANY_ROWS, NO_DATA_FOUND etc.Example-BEGIN Execution sectionEXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line ('A SELECT...INTO did not return any row.'); END; User Defied Exceptions: Oracle also provides the user defined exceptions. This allows you to define custom error handling code in the same manner as the PL/SQL engine handles errors. User defined exceptions are explicitly raised by the user.Declare   v_empno emp.empno%type:=&empno;   v_inc emp.sal%type:=&increment;   v_sal emp.sal%type;   e_High_Sal exception; Begin   Select sal into v_sal   From emp Where empno=v_empno;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 74: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 74/80

  If v_sal>2000 then     Raise e_High_Sal;   End if;  Update emp set sal=sal+ v_inc   Where empno=v_empno;  dbms_output.put_line('Successfully Updated');  Exception   When e_High_Sal then     dbms_output.put_line('Salary is Already High'); End;Explanation-In th above example 'e_High_Sal' is declared as an EXCEPTION. The exception gets raised when the salary is above two thousand. The 'raise' statement makes the flow of execution jump immediately to the exception section (skipping all the statements in between). If the salary is above two thousand, the exception 'e_High_Sal' gets handled through a 'when' statement within the exception section, and displays the message 'Salary is Already High'.Q17.What are the data anomalies in 1NF 2NF & 3NF.Ans. Normalization of data helps in database to prevent corruption of data from the errors that can occur when the database is not normalized. The various errors that can occur when the database is not normalized are insertion anomalies, delete anomalies and update anomalies. These data anomalies are also present in different forms of Normalization, which are:Data anomalies in 1NFExample

Supplier_id Status City P# QuantityS1 10 Patiala P1 500S2 10 Nabha P1 700S3 20 Delhi P2 800

The various data anomalies in the table normalized to 1 NF are:Insertion anomaly: in above table you cannot insert information for a particular supplier until The supplier supplies a product. For example you cannot add the information that supplier s5 is located at ‘nabha’ until you can add a value in the primary key column, P#Deletion Anomaly: - In the above table, if you delete the first Tuple the information about the quantity of product which the supplier supplies, is deleted. In addition the information that the supplier belongs to a particular city is also deleted from the table.Update Anomaly: In the above table the value in the city column is same. If you need to change the city of s1 as ‘bombay’ then you need to search each and every relation in the database and change toe value in the city column. If the value is not changed in each and every relation then the value of the city for S1 may be displayed as ‘bombay’ in a relation and ‘’Patiala’ in another relation.Data anomalies in 2NFWhen you apply 2NF to the supplier table, it is divided into two tables new_supplier and products.Example:- New_supplier

Supplier_id Status CityS1 10 PatialaS2 10 Nabha

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 75: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 75/80

S3 20 DelhiProduct Table

Supplier_id P# QuantityS1 P1 500S2 P1 700S3 P2 800

The various data anomalies in the table normalized to 2 NF are:Insertion anomaly: you cannot insert information for a particular city in the New_supplier table until there is a supplier in the city, since each city has a status.Deletion Anomaly:- you can not delete a row in a new_supplier table since the status information of the sdupplier and city is also deleted.Data anomalies in 3NFWhen you apply 3NF to the supplier table, it is divided into two tables Supplier_city and City_status.Example: - Supplier_city

Supplier_id CityS1 PatialaS2 NabhaS3 Delhi

City_statusCity StatusPatiala 10Nabha 10Delhi 20

Normalizing a table into 3NF prevents data anomalies and provide advantages are:Insertion anomaly: you cannot add information about the status of a city that ‘Patiala’ has a status of 10 can be added even when no supplier belongs to that city. Also new supplier can also be added even though they have not supplied products.Deletion Anomaly: you can delete information about products supplied without deleting information about a supplier or a city.Update Anomaly:- Modifying the location of a supplier or the status of a city requires modifying only one row.

Q18.What are the different control structures supported in PL/SQL.Ans. PL/SQL provides procedural extensions to SQL to implement the following types of control structures: Conditional control via IF statementsIterative control via loops, including FOR, WHILE, and simple loops Sequential control via GOTO and NULL statements The following variations of conditional control constructs are available: IF- THEN If condition then

Statements…End if;IF-THEN ELSE

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 76: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 76/80

If condition thenStatements…

ElseStatements…

End if;IF-THEN ELSIF-ELSE-END IFIf condition then

Statements…ElSEIF Condition then

Statements…Else

Statements…End if;Here is an example of an IF-ELSIF-ELSE statement: IF average_salary < 10000THEN bonus := 2000;ELSIF average_salary BETWEEN 10000 AND 20000THEN bonus := 1000;ELSE bonus := 500;END IF;PL/SQL supports a number of different types of loops: WHILE loops FOR loops (numeric and cursor) Infinite or "simple" loops These constructs allow you to execute the same code repeatedly. You can nest loops within loops. All loops end with an END LOOP statement, which results in a highly structured block orientation for your loops. Here is an example of a WHILE loop which, in turn, contains a FOR loop: WHILE still_searchingLOOP FOR month_index IN 1 .. 12 LOOP calculate_profits (month_index); END LOOP;END LOOP;PL/SQL also supports the GOTO statement and the NULL statement. GOTO transfers control from one executable statement to any other statement in the current program body. This example illustrates both statements: IF rooms_available = 0THEN GOTO no_rooms;ELSE reserve_a_room;END IF;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 77: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 77/80

<<no_rooms>>NULL;

Q19.What are different types of cursors available in PL/SQL.Ans. Cursors in PL/SQL allow you to manipulate data contained within the work area assigned to execute a SQL statement. There are various types of cursors, which are Implicit and Explicit cursors having attributes associated with explicit cursor. PL/SQL support two types of cursorsImplicit CursorExplicit CursorThe tasks that a DBA performs when an SQL statement is executed are:Reserves an area in memory, which is called as the private SQL area.Inserts appropriate data in the memoryProcesses the data in the memoryMakes the memory area free after completing the execution process.Oracle uses a memory area for internal processing of a SQL statement. Cursors allow you to manipulate the data contained within the work area used for SQL operations. The data stored in a cursor is called an Active Data Set.Implicit CursorAn implicit cursor is used when a SQL statement that returns output in a single row is executed. An implicit cursor is declared for SQL DML statement and is queries that return a single row. You can use the implicit cursor for each update, delete and insert statement executed in a program. The open fetch and close statements are performed automatically when an implicit cursor is used.For ExampleBeginUpdate emp set sal=sal*0.15 where empno=&empno;If SQL%found thenDbms_output.put_line(‘Employee record modified successfully’);ElseDbms_output.put_line(‘Employee record does not exist’);End if;End;/Explicit CursorWhen a query is executed the result set can consist of Zero, one or multiple rows. If a query returns multiple rows then you need to declare a cursor explicitly to process the rows. You can declare cursors in the DECLARE section off a PL/SQL block.The open fetch and close statements are used to control an explicit cursor. The OPEN statement is used to run a query associated with a cursor, identify a result set and then position the cursor before the first row. The FETCH statement is used to retrieve the current row and move the cursor to the next row. The CLOSE statement disables a cursor after processing the last row. For Example

DeclareCursor c1 is select * from emp;

Mrow emp%rowtype;Begin

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 78: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 78/80

Open c1;LoopFetch c1 into Mrow;

Exit when c1%notfound;Dbms_output.put_line(‘Employee No’||’ ‘||mrow.empno);Dbms_output.put_line(‘Employee Name’||’ ‘||mrow.ename);Dbms_output.put_line(‘Employee Job’||’ ‘||mrow.job);Dbms_output.put_line(‘Employee Salary’||’ ‘||mrow.sal);End Loop;

Close c1;End;/Q20.What is meant by user defined data type? When we need it?Ans. User defined data types are created by users and define the use of an object associated with it. There are two categories of user-defined data types Object typesCollections typeUser defined data types use the built in data types and other user-defined data types as the building blocks for data types that model the structure and behavior of data in application.Object Data TypesObject data types are abstractions of the real-world entities. An object type is a template and a structured data unit that matches the template is called an object. An object type is schema object with three kinds of components:A Name: which serves to identify the object type uniquely within that schema.Attributes: which model the structure and state of the real world entity. Attributes are built-in types or other user-defined types.Methods:- which are functions or procedures written in PL/SQL and stored in the database, or written in a language like C and stored externally. Methods implement operations the application can perform on the real world entity.Example:Create type address_type as object (street varchar2(50), city varchar2(25), State varchar2(20),pin number(6));To create table of object typeCreate table rough of address_type;object in another objectscreate type person_type as object (name varchar2(25), address address_type); Collection Data TypesEach collection type describes a data unit made up of an indefinite number of elements, all of the same datatypes. The collection types are of array types and table types. Array types and table types are schema objects. The corresponding data units are called:VARRAY’SNested TablesVarray :- Varray is an array of ordered set of data elements. All elements of a given array are of the same datatypes. Each element has an index, which is a number corresponding to the element’s position in the array. The number of elements in an array is the size of the array. Oracle arrays are of variable size, which is why they are called varray.Following steps are used to create varray

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 79: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 79/80

Example :- create a table department, having the columns dept_id, name ,budget, project. The column project is the nested table. This table will store the records of departments. Each project may have more than one project also populate the table with records.Step 1 create an object for table.Create type project as object (project_no NUMBER(2), title varchar2(35), cost number(7,2))Step 2 define varray type projectlst, which stores project objectsCreate type projectlist as varray(50) of projectStep 3 finally create relational table department, which has a column of type project list Create table department (dept_id number(2), name varchar2(15),budget number(11,2), projects project list);Step 4: -Now populate the table with recordInsert into department values(30,’Accounting’,1205700,projectlist(Project(1,’DesignNewexpenseReport’,4150),Project(2,’outsourcePayroll’,16350), Project(3,”EvaluateMergerProposal’,3150),Project(4,’auditAccount’,1225)));Nested tablesA nested table is useful for data model requiring referential integrity and is suited for master-detail and one to many relationships.A nested table is database table in which stores data in it, that cannot be accessed directly.A nested table can be included in a table definition as columns. That is why they are known as nested tables.Nested tables can be manipulated directly using SQL.Syntax to create the nested table.Create type table_name is table of table_name [not null]; Where ; Table_name :- is the name of new table

Table_type :- the type of each element in a nested table.EgCreate type books_type as object(bookno number(4),booktitle varchar2(20),author varchar2(20));create type books as table of books_type;Syntax to define a table using nested tableThis syntax is used to create table using one of its column as nested table.Create table <tablename>(columnname datatype,Columnname tabletype)Nested table <column of table_type> store as store_tableE.g Create table student ( studentno number(4) NOT NULL, student_name varchar2(25),Book issued books)Nested table books_issued store as book_table;Insert row in a table containing nested tableInsert into student values (1001,’amit’,books(books_type(2111,’oracle’,’loney’),books_type(3022,’pl/sql’,’kevin’)));Books is the constructor method for table type books and book_type is the constructor method for object type book_type . Update a nested tableUpdate is used to modify a store table.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100

Page 80: Section Inanoinfotechbanga.com/SecureArea368/upload/qp/oracle_bca... · Web viewIn an E-R diagram attributes are represented by (A) rectangle. (B) square. (C) ellipse. (D) triangle

SUBJECT: RDBMS-II/ORACLE (PGDCA-2, BCA-4) 80/80

The operator allows nested tables to be manipulated using DML when it is stored in a table. The table takes the sub-query as argument and returns the nested table to be used In DML . The sub-query must returns single nested columns.Eg. Update the (select books_issued from student where student_no=1001) Set book_title=’oracle unleashed’ where book_no=2111;Inserting a record in nested table?following command is used to insert record in nested table.Insert into the (select books_issued from student where student_no=1001) values (books_type(4111,’visual basic’,’ ken pol’)));

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.Ph. 0175-2205100, 2215100