You are on page 1of 36
feck sh Sea Ny se Integrity Constraint Over Relations, Enforcing Integrity Constraints, Querying 5 Relational Data, Logical Data Base Design, introduction to Views, Destroying/Altering Tables and Views. Introduction to the Relational Mode! Relational Algebra, Tuple Relational Calculus, Domain Relational Calculus. LEARNING OBJECTIVES i fs Whe ltt siete Introduction to Relational Model neg Basic Terminologies of Relational Model Awe. ae Three Level Architecture of ROBMS 1) cake a Various Types of Integrity Constraints clei pete Introduction to Relational Database Query " . Concept of Logical Database Design and Views: Destroying, Altering and Updating the Views Introduction to Relational Algebra : ; Various Operations of Relational Algebra SoS Kine AE RS ay Sy Introduction to Relational Calculus and its Types. INTRODUCTION 2 od. £0 voerens* Arelational model is one of the, database models that vse ables to store the data in'q/ simple Ways Ig 71/1 simplicity Is due othe usage of tables in which an entity is represented as 6 table (relation) and its insane by the rows of the table (tuples). Relational algebra isa query language which s used to manipulate the data inthe Yelational data model, The queries in relational algebra are formed using set of operators that accets atmos two elation Hstoncss cs arguments ond then reir @ ne relation isonce othe output Thi Broery ef eabakgg the queries using operators helps to easily create a complex query. Relational cole is an example of non- procedural languages, Nen-proceédural language dllows the user to specify what data is required rather thon how 10 get the data, The two types of relational eaebioe are Tuple Relational Calculus and Domain Relational Calculus, + CSG cee. SU Noa Bet ni SNL tency der Srecnun L.4n-omE JOURN FOR ARERR oes 7 ) Stn , i le way. Its simplicity j ‘A felational model is one ofthe database model tat uses tables to store the data in simp icity is the usage of tables in which an entity is represented as a table (relation) and its instance by the rows of the table (tup]. Example '" A students entity is represented as a table whereas an individual student corresponds to the rows in the table, A elation ina relational model consists of, (@ A relation schema (ie., heading of the column) (ii) Arrelation instance (i.e., table). Q2. Explain about various integrity constraints in relational model. Answer : b April-18(R16), The different types of integrity constraints include, 1. Key Constraints A key constraint can be defined as a statement that consist in a table. This set of attributes that work in accordance with the Key constraint is called as candidate key. A candidate key is collection of fields/columns/attributes that uniquely identifies a tuple, z 2. Foreign Key Constraints of minimal subset of attributes that uniquely determine a ary Key in another table. Basically, foreign keys provides a link between two tables and > A foreign key is a set of atributes or single attribute in one relation ther forms candidate k ‘mother relation. For example, consider another relatiog “DEPARTMENT” wit, attributes (Dname, DNo, Manager id), 3. General Constraints ‘There are two types of general constraints. (a) Table constraint (b)_Assertions ‘Table Constraints These are applied on a particular table and are checked every time that Assertions specific table is updated. These assertions are applied on collection of tables and are checked whenever any one of the table is Q3. Define the terms primary key constrains and foreign key and check constraints, “updated Answer : Primary Key Constraints Primary key constraint is used to define a column or group of columns that can distinctively ‘identify every row in Syntax CREATETABLE table_name (coll datatype NULL/NOT NULL, col2 datatype NULL/NOT NULL, CONSTRAINT const_name PRIMARY KEY (coll, col2, ... coln)); me (column_namel, column_name2, : : Here, coll, col2, col3 represents the column name that defines the primary key. WARNING: ‘of this book is @ CRIMINAL act. Anyone found guity is LIABLE to face LEGAL ” : Xerox/Photocobying ‘ween i same table : ie ime he or between distinct tables. Inorder to define a Syntax "CREATE TABLE table_name (coll datatype NULL/NOT NULL, col2 datatype NULL/NOT NULL; 1 1 1 coln datatype NULL/NOT NULL, CONSTRAINT fk col FOREIGN’ KEY (coll, col2, ..coln) ¥ REFERENCES primarykey_table (coll, col2, ... coln) % ‘Check Constraint This constraint is used for data validation when a new value is inserted into a table. Consequently, it checks wh specified condition is satisfied or not. If the condition is satisfied then the data is accepted by the RDBMS; ‘otherwise the not accepted an error message is produced, Example r . \ i wos EMP_SAL INTEGER check (emp. sal in (‘20000", *17000", “25000")) 19 This code checks whether the emp_sal lies within the given range of values 20000. 17000 and 25000. Q4. What is logical database design? Answer : - Any entity-relation (ER) diagram can be converted to relations/ tables. A logical database consist of attrib relationships which all together describes a database. Based on the approaches discussed below on ER diagram it can be! toaset of tables where each entity represents a relation and attributes of entities represents the columns of the relation. Q5. Write brief notes on altering tables and views. OR Explain views in SQL language. (Refer Only Topics: Views, Creation of Views) Answer : ALTER Table ALTER TABLE command is used to modify the structure of the table or view. Syntax ALTER TABLE Tablename ADD [COLUMN] Columnname datatype DROP [COLUMN] Columnname RESTRICT/CASCADE ADD [CONSTRAINT] Constraint name DROP [CONSTRAINT] Constraint name RESTRICT/CASCADE _ {ALTER [COLUMN] SET DEFAULT Default option] A herent ts {ALTER [COLUMN] DROP DEFAULT] r 9 cee specrnan att One JOURNAL FOR ENGINEERING ~ asitgg St ne pile 20005: SFT oviglwl Hitt WOlat off (© Addition of constraint «frags a f (4) Deletion of constraint Q ei (©) Setting a defaitt value for column (®) Unsetting a default value for a column, Views Views are derived or virtual tables, they does not exist and derive their data from the original Aun 2 a “Ser fo See only the part of data but not all data. The user Can think of view as any other normal relation and can perform Operations that can be performed relations. Views are dynamic in nature Le, the changes/modifications made to the views reflected back to the original table and vice-versa, Creation of Views The following SQL statements are used to create a view. i? CREATE VIEW (view name) (field, field2, field n) AS SELECT (attribute 1, attribute2, FROM Table1, table2, WHERE : . attribute n) ‘i . table n ' ‘Q6. List the differences between relational calculus and relational algebra, Answer : Model Papers, ai Relational Calculus faci gale eae eg Algebra 1. | Ttis'anon-procedural or declarative language 1.) | Teis a procedural language 2. | Itallows the programmer to specify what 2. "allowsthe programmer to specify what data i | data is to be retrieved but not the way of required and also-the way of retrieving it, retrieving it : 3. | ‘tis possible to express all relational algebra 3. | Iris restricted to safe queries on the ealeulus ; queries into relational calculus, aa 4. | Ibis mostly preferred by the end users 4] ,Jtis mostly preferred by the programmers, : 5. | ttis superior to relational algebra, 5, Itis inferior to relational calculus, Q7. Explain domain relational calculus. Answer : A wig DRC is similar to TRC but the only difference is DRC make use of domain variables‘instead of tuple vari Yariables are those variables which are defined for the domain Value ofthe attributes, For example the attribute ‘variable which take the tuple values fim the relation but when i comes to DRC the anus “age” will take its domain —int- QBE (Query-by-example) is language which makes we'of DRC where us SOL ( is based on TRC. a Oe UNITA2: Introduction to Relational Model, Relational Algebra 8, List the primitive operators in relational algebra. Answer # (Model Papert, (4) | May-18(R13), at(c)) The relational algebra defines three primitive operations namely, (i) Select The symbol for the select operation is. This operation is used to select particular rows from the two relations which satisfies the given condition, Syntax 5 sexism tAblename (i) Project This operator is used to display the list of attributes/ columns defined in the relation R. Syntax Texinan (table Join (ii) Joins are used to combine the information of two relations which have at least one field in common. It is ‘one of the most important operator of RDBMS Q9. What are joins? List the four different join operators. Answer : Joins are used to combine the information of two relations which have at least one field in common. It is one the most important operator of RDBMS. In simple words, a join operation can be defined as a Cartesian product followed by selection or projection operators. The different forms of join ‘operators are, (a) Conditional join (Meta join 8) (b) Equi-join {c) Natural join (4) Outer join Q10. Describe about outer join. Answer : May-16(R13), 01(¢) Outer joins are the special variant of “join” operation that fre dependent on NULL values. Generally, a ‘join’ operati Performs the cross product of two tables and apply certain join Condition, Then it select those rows from the cross product that Salisfies the given condition. But with outer joins, DBMS allows the user to select those rows which are common (satisfies the Biven) and even those rows that does not satisfies the given ondition, SPECTRUM ALLAN-ONE JOURNAL FOR ENGINEERING STUDENTS “There are three types of outer joins namely. (i) Left outer join (ii) Right outer join ii) Full outer join. G11. Let R= (ABC) and S = (DEF) let r(R) and s(S) be relations on schema R and S. Give an expres- sion in the Domain relational calculus that is equivalent to each of the following, () oa") F (i) TH Geol *8)) Answer : April-18(R16), Q1(d) Given that, R=(ABC) S= (DEF) 1(R) and s(S) are relations on schema R and S'respectively. @ o,.,A0) { | ernb = 25) Gi) TL (<5) T1,Ao¢. (7 * 8) ‘The domain relational calculus equivalent for the above expression is, {(a,b, cd, €f)}| 3a( era INK Account number of customer Bname — Branch name Amt — Amount . Instance of a Relation A set of records or tuples having exactly the same number of fields as the relation schema is called a relation i Number of fields in each tuple = Number of fields in a relation schema aa The instance ‘C,’ of the customer's relation mentioned above is given as, Fields Cid Cname Aceno Bname Atnt Si 6001 | Shazia 41 uni 1500.00 , 6312 | Zainab 52 SBI 2000.5 Tuples| 6448 Aasia 60 SBH 10500, $i i 6015 | Neelima 72 Darussalam Bank |’ 18050.50 Figure: Customers Relation Instance C, with Degree = 5 and Cardinality WARNING: xerox/Photocopying of this book is & CRIMINAL act Anjone found guity i LIABLE fo Face LEGAL proces UNIT-2 Introduction to Relational Model, Relational Algebra Requirement of the Relational Model Each relation must be specified using distinct tuples which can be in any order. Domain Constraints Domain constraints in the relation schema are the set of conditions that must be satisfied by each instance, Hence, the field domain indicates the field type through which all the values of the columns can be derived. An instance of R(fl : Dl, £2 D2... fi: Di) given as {afl dl, £2: a2, .., fi: di>| dl © Domi, d2 € Dom?, die Domi} Where, Domi = Set of values of the domain Di <>=Tuple’s field { }= Set of tuples |= ‘Such that’ e= ‘in’, Degree of Relation Itrepresents the number of fields in a relation. Itis also known as Arity. Cardinality of a Relation Instance Itrepresents the number of tuples in an instance, Relational Database and the Relational Database Schema A relational databa having a unique name whereas the relational database schema refers to the relation schema collection. ‘onsist of several relations each Example A college database contains the relations such as Stu- dents, Professors, HODs, Teachers, Examiners, Guides ete A relational database instance is group of instances where each relational schema has one instance that satisfies the domain constraints. Q13. What is relation? Di relation schema and ri the term unity and degree of a relation? What are domain constraints? Answer : Relation Relation can be defined as a set of records that provides the description about the data, If data is described in terms of data model, then itis referred as schema. A relation in relational model consists of, (i) Relation schema (ii) Relation instance. (Relation Schema For answer refer Unit-II, Q12, Topic: Relational Schema, (ii) Relation Instance For answer refer Unit-I, Q12, Topit: Instance of a Relation, May-17(R15), 03(0) ais ae Unity of Relation ih ‘The degree of association or relationship represents the self and dicecthierarchal relationship between the sub directories of a root directory. . Degree of Relation It represents the number of fields in a relation. It is also known as Arity, : Domain Constraints : For answer refer Unit-Hl, Q12, Topic: Domain i Q14. Explain the relational database architecture. Answer: May-16(R13), Q2 Relational Database Management System (RDBMS) supports three-level architecture as shown in figure. The levels supported by this RDBMS are Physical level, Logical level and External level. These levels are separated by physical and logical data independence, Physical data Logical data ome oe Base Table with indexes [View 1 Base Table with indexes AX! ime Physical level Logical level aan External view can have any number of base tables and/or views. These views are logical tables visible to the users, This fact should not be known to the users. ‘The logical level contains physical base tables. These tables are managed by the Database Administrator (DBA) By using the DDL (Data Definition Language) commands like CREATE TABLE command, ALTER command ete, A base table can have any number of indexes. These.indexes may be created by the system or by the Database Administrator by us- ing the CREATE INDEX command. These indexes are mainly used to increase the retrieval speed. An index contains indexed column(s) values. By using these values, the records are located. Hence, the records are retrieved very fast depending on the value ofthe column. B trees or B+ trees are most suitable for indexes. Physical level contains files. These files has base tables and their indexes. The physical representation tables is not similar to base table that contains rows and columns like spreadsheet. Here, the rows corresponds to Physically stored records but the ordering and other details of storage may change. The data files and indexes are managed by the DBMS but not the OS. The user has no knowledge of these indexes and their maintenance. The DBA is one who creates views for users by using the CREATE ‘VIEW command. These view tables or Virtual tables are not stored permanently but are created only when the user Warts access, SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS =) ae ee Apeimay-A2, Set, a3(a) construct i 6 fades that enables the definition ofa relation Creating Relations in SQL(Structured Query Language) Relations (tables) are cr whee reated in SQL using Create Table Example bi Create Table Customers(cid INTEGER, Cname IAR(30), Accno INTEGER, Bname CHAR(40), Amt REAL); The SQL constructs that allow modification of relation instances are as follows, 1. Inserting Tuples in a Table ‘Tuples are inserted using an INSERT command in a table. Example INSERT INTO Customers(Cid, Cname, Accno, Bname, Amt) VALUES(6001, ‘Shazia’, 41, ‘UTI’, 15000,00); Note Listing of columns is not compulsory. 2. Deleting Tuples from a Table ‘Tuples in the table can be deleted using a DELETE com- mand. Example DELETE FROM Customers C WHERE C.Accno = 41; 3. Modifying the Column Values Values in a particular row can be changed using an UP- DATE command. ‘The key words WHERE and SET are used to determine the modifying rows and the modifying procedure (i.e., how the rows can be changed) Example ‘When a customer deposits some money in his account its instance can be updated as, UPDATE Customers C SETC.Amt Amt + 1000 WHERE C.accno <= 60; Figure: Customers Instance C, After Performing UPDATE Operation WARNING: XerouPnotocopying of his book @ CRIMINAL act Anyone found gully is LIABLE to face LEGAL procend™™ briefly integrity constraints ove, ie tae i AprilMay 42, Set2, ay) OR Compare between Super key, Candidate key, Primary Key for a relation with examples, (mip ake: Spor Ke Cake Ke Primary hea May-19(R16), ax) Integrity Constraints Over Relations Integrity constraint is a Condition that ensures the cor rect insertion ofthe data and prevents unauthorized data access thereby pressuring the consistency of the data. Example The roll number ofa student cannot be a decimal value, The database enforces the constraint thatthe instance of roll ‘number can haye only integer values Integrity constraints can be enforced and specified inthe following cases. (a) Assoomas the database schema is defined, the associated integrity constraints must be specified (b) Validity of the changes made to the data must be checked while executing the application The different types of integrity constraints, in addition to domain constraints include, 1, Key constraints 2, _ Foreign-key constraints 3. General constraints 1. Key Constraints key constraint can be defined asa statement that consist of minimal subset of attributes that uniquely determine a record in a table, This set of attributes that workin accordance with the key constraint is called as candidate key. (a) Candidate Key A candidate key is a collection of fields/columns! attributes that uniquely identifies a tuple. For example, in“ Customer” relation the attribute “Cid” is a key which luniquely defines a tuple in a relation, No two rows in relation “Customer” can have the same “Cid” value. THE ‘set of attributes that form a candidate key need not be all keys, The attributes may be treated as candidates 10 be taken as key. For example, the set (Cid, Cname) is candidate key which means either Cid or Cname ca” PE taken as key but not both, each of them independently and uniquely identifies a particular row. The altermat keys are the candidate keys that are not taken #°™ \ \ ‘UNIT-2_ Introduction to Relational Model, Relational Algebra (b) Composite Key ‘Composite key consist of more than one attribute. that uniquely identifies a tuple in a relation, Ail the attributes that form a set of keys and all of them taken together determines a unique row in a table, For example, the set (Cid, Aceno) is a composite key which maintains the uniqueness of each row. Both Cid, Aceno are taken as keys. (©) Super Key A super key is a combination of a candidate key and a composite key i¢., super key is a set of attributes or a single attribute that uniquely identifies a tuple in a relation. For example, consider the super key, {Cid, Aceno, Cname} Here, all the three attributes taken together can identify a particular record or a combination of any two attributes can identify a particular record or any one of the attribute ‘ean identify a particular record. (@) Primary Key Only a single attribute can uniquely identify a particular record. More specifically, it can be defined as the can- didate key which has been sclected as key to identify 1” attribute in "Cus- unique records. For example, tomer” relation can be treated as a primary key. Universal Set = Keys Figure (1: Representing Relation between Different Keys Defining Key Constraints In SQL, one can eliminate the insertion of duplicate data ‘by using a UNIQUE constraint. This constraint helps the user to ‘insert unique values for the columns which have been declared 4s UNIQUE, forming a candidate key any one of the columns mong them can be declared as primary key by using primary ‘key constraints. Bee Example : Consider the creation of “Employee” table, CREATE TABLE Employee (Enamé CHARGO)), Bid INTEGER, Bdate DATE, Address CHAR(30), DNo INTEGER, ‘Age INTEGER, Phone_number INTEGER, UNIQUE (Eid, DNo), CONSTRAINT key PRIMARY KEY (Eid)); This example shows the creation of employee table with attributes Ename, eid, Bdate, Address, Dept Number (DNo), Age, Phone_Number, UNIQUE key constraint is used on columns Eid and DNO which ensures that the values inserted in these columns are unique. The last line of decla- ration defines a primary key constraint. The syntax used for defining constraint is, CONSTRAINT Constraint name PRIMARY KEY (key) ie., CONSTRAINT key PRIMARY KEY (Eid). This line declares Fid as primary key for the “employee” relation. If the user inserts repeated values for “Eid” then error ‘occurs and constraint name is returned indicating yiolation of constraint. 2. Foreign Key Constraints Foreign key serves as a primary key in another table. Basically, foreign keys provides a link between two tables and are used to maintain data consistency. A foreign key is'a set of attributes or single attribute in one relation that forms candidate key in other relation. For example, consider another relation “DEPARTMENT” with attributes (Dname, DNo, Manager id). Here, (DNo, Manager id) is the Candidate key. DNo refers to the dept number to which a particular employee be- longs manager_id refers to the manager who is responsible for controlling the department. And therefore, the two tables ‘employees and departments are related to each other by DNo and Manager_id. Since foreign keys are used to ‘maintain data integrity if, for example there are some changes made to “Employee” relation (like changing the deptnumber of some employee who is also the manager of the same department), then these changes ‘must also be done in relation “Department” and hence this must be modified. SPECTRUM ALLIN-ONE JOURNAL FOR ENGINEERING STUDENTS | ae Bane Address ge_| Phone number 12345261 | 108-1965 | New Jersey a_[ 7ansz8 12sasa62_ [12-1955 | Chicago si [773313218 12345263 |” 20-11-1973 | New York 34 | 773421317. Bill 12345268 | 2541055 | Detro si | 773271842 Donald | 12345267 | 028-1968 | Deiro 28 | _ 773423145 ail 12345366 | 044-1965 | New York 41 | 773291828 Figure (2): Table Representing Employee and Department Relations ‘The relation Department is using “Manager_id” as foreign key to match the “Eid” of the employee relation. Its not a compulsion that every tuple that exists in employee relation should match a tuple in department relation, But the reverse shared Satisfy this condition i.e, all tuples in department relation must match all the tuples in employee relation. The department relation 1s called as referencing relation and employee relation is called as referenced relation. With the concept of foreign key, tuples can be inserted and deleted by ensuring that foreign key constraint is not violated, — For example, if the insertion of a Manager_id 12345269 in department relation, then the DBMS must avoid the insertion of this. tuple as no such Eid-12345269 exists in employee relation. In another case, if one want to delete the Eid 12345261 from employee relation, then again it must also be deleted from department relation or else the department relation will contain the Manager_id of the deleted employee. These two cases shows the possibility of violating foreign key constraints. Further, a foreign key can be used as a reference for some relations. In this case, itis called as self-referential key. For example, itis possible to add another field namely “teammate” in employee table which refers to the Eid of the employees who are working as a team for the same projects. Now, this field can be declared as foreign key and refers to the primary key “Eid” of the relation, In case, if there are no teammates then one can use NULL values. Defining Foreign Key Constraints in SQL Syntax for applying foreign key is as follows, CREATE TABLE Department(Dname CHAR(30), DNo INTEGER, Manager_id INTEGER, PRIMARY KEY (DNo, Manager_id), FOREIGN KEY (Manager. id) REFERENCES Employee) ‘The statement FOREIGN KEY (Manager_id) REFERENCES Employee - means that the foreign key “Manager id” uses primary id “Bid” of employee relation as a reference: Every tuple with Manager_id must match a tuple in employee relation. 3. General Constraints ‘There are two types of general constraints, (a) Table constraint (b) _Assertions. Constraints a wa applied on.a particular table and are checked every time that specific table is updated. Assertions ; : ‘These assertions are applied on collection of tables ‘and/are checked whenever any one of the table is updated. WARNING: Xerox/Photocepying of this book Is 2 CRIMINAL act ‘Anyone fot Jund guilty is LIABLE to face LEGAL proceedings. 17. Explain in detail about forcement integrity constraints. Answer = Enforcing Integrity Constraints Integrity constraints are the rules that wher prevent deletion and upklation of consistent data t ‘when applying integrity constraints on rel 4 n applied on relations restricts the insertion of incorrect data. They also help a hat may lead to loss of data integrity, And, therefore one should be very care! ions, | The operations such as insertion, deletion and updation must be discarded ifthey are found to violate integrity constraints. ‘This section provides a brief knowledge on different violations of ICs and also the solutions to handle these violations. Example Consider the Employee relation where “Eid” is the primary key, The following statement, INSERT INTO Employee(Ename, id, Bdate, Address, DNo, Age, Phone_number) VALUES(‘hansen’, 12345265, 12-12-1975,” ‘New Jersey’, 8, 31, 7732132187); This violates the primary key constraints as cid with 12345265 already exists in the same relations. Since “Eid” isa primary key, its value must be unique for every tuple of relation. Moreover, a primary key cannot contain a null value. Insertion of null values for the field “Eid” again violates the primary key constraint. The following statement shows the same, INSERT INTO Employee (Ename, Eid, Bdate, Address, DNo, Age, Phone_number) , VALUES (‘hansen’, null, 12-12-1975, ‘New Jersy’, 8, 31, 7732132187); The statement given below, INSERT INTO Employee (Ename, Bid, Buate, Address, DNo, Age, Phone_number) VALUES (12345, 12345260, 12-12-197: “New Jers 8, 31, 7732132187); Causes a violation for domain constraint as the domain for ename in character but the inserted value is an integer. Their domain constraints is not satisfied again causing a violation. So, while inserting values into the table one must take care of primary ey, domain and unique constraints. When applying any update operation all these violations may again Come into picture, But with delete operation - no primary key, domain and unique constraints are violated. Example for Update Operation UPDATE Employee E SET E Bid = 12345263 WHERE E.Eid = 12345267, statement causes the violation and hence rejected because the employee with 12345263 already exist. Performing this updation means violating unique constraint for primary key. In shor it can be suid that - these rules are collectively called as-entity integrity rules and must be appropriately applied. The second rule called as - referential integrity rules are applied as foreign key, This rule states that either foreign key values ‘muist be null or must match the values of the primary key attribute, To understand the concept of referential integrity,consider the Same two relations ~ employee and department where the foreign key ~*Manager_id” uses Eid of employee as a reference, The following statement, “INSERT INTO Department(Dname, DNo, Manager id) VALUES (‘headquarters’, 9, 12345260); This causes the violation of referential integrity as no sich Eid-12345260 exist in employer relation, Thus, insertion in ent fables violates the integrity rule, But insertion in employee table does not violate any referential intepity rule, This Points reversed for deletion operations. That is deleting «tuple from department table is as simple — its nota compulsion that ‘hetuple delete from department must also be deleted from employee relation. Whereas, when a tuple is deleted from Employes ‘elation —then it must also be deleted from department table otherwise department table will contain the information about the deleted employee - which may lad to daa inconsistency. However, the application of update operation which may rt the, Todiication of pemary key (Ed) either in department or employee relation may led t violation of a hi , Name Phone number) Gitaay GBince> Figure: ER Diagram Representing Relationship Between Lecturer and College into relations. The attributes of this relation consist of primary keys of all other This ER diagram can be converted into three relations namely, lecturer, college and works in with following attributes. Lecturers (Lecturer_id, Course id, Dept, Name) College (College_id, Name, Phone_number, Address, No_of dept) Wotks-in (Lectures id, College id, Since) The following are SQL statement for creation of relation — works-in, All the attributes of works-in relation taken together form super Key. Underlined attributes of works-in relation form the set of candidate key, CREATE TABLE Works-in (Lecturer id INTEGER, College _id INTEGER, Since DATE, PRIMARY KEY (Lecturer id, College id), FOREIGN KEY (Lecturer _id) REFERENCES Lecturers, FOREIGN KEY (College id) REFERENCES College); Works-in Lecturer_id | College id | Since 1 10-8-1985 n 254-2000 B 12-4-1999 |_01-01-2006 (© Translating Relationship Sets to Tables with Constraints ‘When relationship sets (without constraints) were translated to relation, then the key for the resulting relation was the bination of two keys ofthe participating entities: Bul when some key constraint exists then translating a relationship et toa lon should be done carefully In general, if thee ae ‘A enttes in a relationship set and only *? of them ate connected to the ‘tionship set, for which a relation i to be created, then any one of the key ofthese“ entities forms the primary key for the ing relation and set of keys of these‘ entities forms the candidate ke. That is, we have? candidate keys for ese relation ‘nly one of them is assigned as a primary key. B Ben. 9) SPECTRUM A@LLIN-ONE JOURNAL FOR ENGINEERING STUDENTS or Tounderstand his cone, conser he fllowing ER ding. Lectures contro sean Ths ‘ment entity and lectures entity are related via a “Control” relationship set ereate ay are connected via arrows (o this relat sel involves thre entities namely stent, lecturer, department But only two them areconnne TN Ah “sel (ecturer and department) so, the cade key forthe resulting relation consist of Set OF Pe ‘only one of them is assigned as primary Key. Student | cams | 5 HOD. Figure: ER Diagram Representing Different Relation: Controls (Lecturer_id, DNo, Since) Lecturer_id and DNo — candidate key. Each department has only one HOD- Head of the department who is also a lecturer — no two rows in a table can the same DNo but can have same Lecturer_id because a lecturer who belongs to CSE and department can also belong to ‘department but in both the cases the DNo is different. He can teach CSE, CSIT courses as well. So, Lecturer id does not uni ‘identifies a tuple in relation ‘Controls’, but DNo does so, therefore DNo is the primary key for the relation ‘Controls? SQL statements for the creation of table controls CREATE TABLE Controls(Lecturer_id INTEGER, DNo INTEGER, Since DATE, PRIMARY KEY (DNo), FOREIGN KEY (Lecturer_id) REFERENCES Lecturers, FOREIGN KEY (DNo) REFERENCES Department; ip Sets Controls 12-4-2002 23-4-1998 17-5-2004 05-05-1995 | 28-08-2000 The above table isthe new relation to which a relationship set is mapped. Another approach to deal with this of information (fields) othe existing entity instead of creating anew relation Each department ia controlled by the fields “Lecturer id” and “Since” from Lecturer and Controls respectively to department entity: Now the will have the information of both the relations (lecturer and Controls) - all the queries can be answered with relation ~thére is no need of combining two relation. The disadvantage of this approach is that if mo HODs are g 4 lot of space is wasted - in the sense that NULL values has to be entered for every department if no 4— Mechanical S-EEE 1 ~ Aeronautical WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face | a — tf “ a ca : {tatement for creation of Department! which combines the information of Department and Controls, & CREATE TABLE Department 1 (DNo INTEGER, ~e a Dhame CHAR(3O), an Course_id INTEGER, HOD CHAR (30), Lecturer_id INTEGER, Since DATE, PRIMARY KEY. (DNo), ; FOREIGN KEY (Lecturer_id) REFERENCES Lecturers); Note Lecturer_id can take NULL values, (@ _ Relationship Sets with Participation Constraints to Tables Participation constraints are rules that must be followed by all the participating entities. Converting an ER diagram with participation constraints is quite easy. Consider the following ER diagram, ram Representing Relations with Participation Constraints. Every college need to have one principal i.e., principal is a coordinates/manages ¢olleges and also are the employees who Workin colleges. This is a participation constraint, The key constraint is that a college can have only one principal (Unique). The following SQL statements are required to create a relation that also includes a participation constraint, CREATE TABLE College(Cid INTEGER, Cname CHARG0), : * Clocation CHAR(30), Pid INTEGER NOP NULL, Since DATE, PRIMARY KEY (Cid), FOREIGN KEY (Pid) REFERENCES Principal ON DELETE NO ACTION); Ase have declared P_id as NOT NULL, it cannot take null values, indicating that each and every row of college should ™*P the rows of principal. Thus, satisfying the participation constraint (every college must have a principal), The ast statement ON DELETE NO ACTION in used to specify that whenever a delete operation i performed on principal ‘She itis rejected ic, if that row of principal is also present in college then the delete operation is rejected. Ifthe use cat {eTomm the delete operation on principal, he must be ensure thatthe row to be deleted does not exist in college. The user have “ssign a new principal (P_id) in college relation then he can delete the previous P_id from principal. A new réward must be ‘teed in college to have a new employee as a.principal. pecan. SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS. es : 7 DATABASE M/ a Converting ER Diagrams with Weak Entity Sets to Relations primary key attribute of an A weak entity is one which is dependent on other entities for its identification Cae with ie ritriine(pitary ke any ats tify each and every tuple uniquely But he combination af weaken abe wi TUE A ity identifies each tuple uniquely in weak entity ~ thus weak entity is depen key and uniquely determines ial key is the name piven tothe attribute of weak entity which acts as & primary identifying owner entity. Consider the following ER diagram, tuples of the Program oous> esr) re: ER Diagram Showing Relationship Between Weak Entity (Output) and Identifying Owner ee ‘The ER diagram shows the weak entity (output) is dependent on program entity. The processing or execution of a prog will give the output. The partial key for output entity in Prog name, Since two programs can have same name; this attribute c ‘not identify the tuples of output uniquely. But the combination (Prog_number, Prog_name) can be used to determines the tup Uniquely, The special property of weak entities is that when a owner entity (program on which it is dependent) is deleted, the weak entities are also deleted. That is, if program, is deleted then output is also deleted. The following are the ‘SQL statements which translated on ER. diagram with weak entities to a relation, ‘CREATE TABLE Output-weak (Prog_name CHAR(30), Errors VARCHAR(20), Result VARCHAR(30), Processing_time TIME, Prog_number INTEGER, PRIMARY KEY (Prog_name, Prog number), FOREIGN KEY (Prog_number) REFERENCES Program ON DELETE CASCADE); The keyword CASCADE indicates that whenever a tu (relationship set) and output (weak entity) are also deleted. The identifies the output for a specific program. (Prog_number cant (© Converting Class Hierarchies to Relations (Class hierarchies in an BR diagram refers to the conce attributes of base entity in addition to its owh attributes. Cor iple in program is deleted, all the related tu Primary key is set of (Pro; not take NULL values), ples in processin _number, Prog_name) which uniquel Pt of inheritance (isa relationship). The child entities inherits all msider the following ER diagram, aa * No_of_children Saky>—| Employee [Pweat urrame) _ " Fowre: ER Diagram Representing I A Relationship < WARNING: Xerox/Photocopying of this book CRIMINAL et Ant iy W LBL A LEGAL @ Person (Name, Address, Profession, Sex, Acc_mumber) a ‘& Employee (Eid, Salary, Company name, Experience, Account_number, Name, Address, Profession, Sex) . Parent (Sumame, Dependents, No_of children, Acc_number) 4 ec ares! Ifa tuple of base entity is deleted, then itis also deleted from sub entities ‘The second approach deals with creating only two relations, second for parent. In this case, the e elation corresponding to employee will ‘ole following st psc and the attributes of base entity, ‘nonew relation is created for base entity. The relation corresponding to parent contains its own attributes. bAs ‘The first approach is easy and simple to follow if data of same person has to be collected then examine the person relation. Andif about a working parent has to be collected then go in the relations in order to get the information with second approach. ‘The probability of getting redundant increases, if data about the working parent has to be called then the attributes ~name, sdires, profession, sex are stored twice and hence this redundant data may lead to update, insert and delete anomalies. The second paint to note here is that it is impossible store the information of some person who is neither an employee nor a parent. : The use of two approaches depends wholly on the data and the operations to be performed on that data. . (@ Converting ER Diagrams with Aggregations into Relations ies An aggregation represents a relationship between two relationship sets. That is, one relationship set participates in other relationship set, this participates is termed as aggregation. i Consider the following example, ‘ Gm GED Figure: ER Diagram Representing Aggregation ‘From this ER diagram five relations are created as, i Principal ® Lecturers _,_. The attribites of works-in relation are the key attributes of Lecturers (L_id) and attributes (Since) ive, (a) Works-in (Lid, Cid, Since) (b) Principal (Name, P_id, Salary, Qualification, Age, Cname) (©) “Lecturers (Name, L_id, Course, Salary) (A) College (Cid, No_of dept, Name, Courses_offered, Clocation) . To create « relation for “Controls” relationship set, the following attributes are added to its set, (i) - The key attributes of works-in relat (ii)_Its own attribute (Since) and key attributes of Principal. Therefore, (©) Controls (L_id, Gid, Since, P_id) To make matter simpler, itis worth to note that all the information of works-in relation can be collected from “Cont relation, Therefore, it is possible to drop “work-in” relation, making it more simple and understandable. 2.1.4 Introduction to Views, Destroying/Altering Tables and Views Q20. What is a view? Explain briefly. Anower.2 ‘Model Papers, Views Views are derived or yirtual tables, They do not exist and derive their data from the original relation. They allow the to see only the part of data but not all data, The user can think of view as any other normal relation and can perform all the erations that can be performed on relations. Views are dynamic in nattire i., the changes/modifications made to the views: reflected back to the original table and vice-versa Creation of Views "The following SQL statements are used to create a view CREATE VIEW (view name) (fieldl, field2,..., field n) AS SELECT (attribute1, attribute... attribute n) FROM Table!, table2,.., tablen WHERE ; This is the general format for defining a view. Example Fores iple, view is created for employee table The following view gives the information about the project located at New Jersy. CREATE VIEW Project_info (Name, 1d, DNo, number, PName) AS SELECT E.Ename, E.Bid, E.DNo, PPNo, P.PName FROM Employee £, PROJECT P WHERE E.Eid = Pid ANDPLocation = ‘New Jersy"; The view Projet. info contains the following elds, Name (of employee who are working on project, ld, DNo, Na Id Name | DNo | Poumber PNante 12345263 Green 7 st Softdrinks 12345262 Jack i ma Product B Project_info View This view can be treated as any other relation and queries can be evaluated Based on this statements relations can also be applied to views, The RDBMS converts the eee Se i query to equivalent operat ations, difference being the RDBMS menges the two queries, query defi peration and retumns a re ined by the user and iginally defined whe definition was created. a WARNING: XeroxPnotocopyng of his books 8 CRIMINAL ac. Anyone found uit LIABLE face LEGAL es Droject_info View is already created as, CREATE VIEW Project_info (Name, Id, DNo, Prumber, PName) ; _-ASSBLECT E-Ename, E.Bid, E.DNo, PPNo, PPName : on FROM Employee E, PROJECT p . WHERE E-Eid = PEid AND PPLocation = "New Jetsy"; ‘And now if'the following command is issued, . — SELECT * FROM Project info where DNo = 7: = j ‘Then RDBMS will translates it to the following statement a SELECT Name, Id, DNo, Pnumber, PName mY FROM. Employee E, Project P where DNo = 7 AND E.Eid = P.Eid AND P-PLocation = ‘New Jersy’; RDBMS will evaluates the query and then returns the relation consisting of all the tuples which satisfies the given condition. ‘Advantages of Views (@ Views provide data security — as views contains only a part of data, the data of the base table is protected from the unau- thorized users as they can access only the part of data not all the data. (0) Different users can view same data from different perspective in different ways at the same time. (9, Views can be used to hide complex queries such as the queries which involves “joins” operation. The user can issue the simple queries for the views and RDBMS will take care of the complicated process. (4) _ Views can also be used to includes extra/additional informations. 021. Explain updates on views briefly. Answer : Performing Updations on Views Whenever updations are performed on views, the changes must reflect back to the base relations. Similarly when changes are made to base relation then these changes must reflect in all the views which are derived from this base relation! | * - But all the updations cannot be applied on views. The updations can be carried out only on the update table views. An ‘Update table view is one which is derived from single base relations and if the following are true for the update table view, {9 Nocolumn should be derived by using as aggregate function (©). Nocolumn of the view should be derived from the expression if the expression involves scalar operator or scalar functions. ‘On such views insert and update operations are not allowed. ’ {9 Definition of view should not involve DISTINCT keyword. (4) Definition of view should not include as GROUP BY or HAVING clause, {9 Definition of view should not includes a sub-query that involves the base relations, heck Option CREATE VIEW emp(Name, Id, DNo, Bdate, Salary) AS SELECT E.Ename, E.DNo, E.Bdate, E.Salary FROM EMPLOYEE E 3 WHERE E.Salary > 20,000; ee * snp lting a row in emp, it can take NULL values for the fields that are not present in emp. Similarly, deleting a row from by deleting a row from emp relation. With check option SQL provides a way to user fo insert correct data so that but gat OF Updated data does not violate the view-definition. For example, inserting a row in emp which is hiasy auttonshe 7 ‘hat if the row does not satisfy the given condition, the check option is used to check these conditions. ‘ SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS Q22. Discuss about destroyinglaltering of tables and views. OR and destroy tables and views What are the SQL constructs to modify the structure of tables Aoriiay-12, Set, OR How to destroy and alter tables in a DBMS? (Refer Only Topics: Destroving Tables, Altering Tables) Answer : Destroying Tables Destroying a table can be done with the help of DROP command. Syntax, DROP TABLE table-name RESTRICT/CASCADE The keywords RESTRICT or CASCADE must always be used with DROP command. Example + DROP TABLE Department RESTRICT This command delete the Department table if some view or IC is referring to it otherwise, this command fails. * DROP TABLE Department CASCADE : mn this case all views and ICs referring to the relation ‘Department’ are deleted along with the table. Destroying Views ‘A view can also be destroyed with the help of DROP command. Syntax DROP VIEW View name Example Drop View Project_info. Altering Tables ALTER TABLE Command is used to modify the structure of the table. ALTER TABLE Tablename ADD [COLUMN] Columnname datatype DROP [COLUMN] Columnname RESTRICT/CASCADE. ADD [CONSTRAINT] Constraint name. DROP [CONSTRAINT] Constraint name RESTRICT (CASCADE [ALTER [COLUMN] SET DEFAULT Default option] (ALTER [COLUMN] DROP DEFAULT] With Alter command following modification can be done (a) Addition of column (b) Deletion of column (©) Addition of constraint (d) Deletion of constraint (©) Setting a default Value for a column () Unsetting a default value for a column. Example ALTER TABLE Employee \ ADD Project_number INTEGER ALTER TABLE Employee ALTER GENDER GENDER SET DEFAULT ‘M’, WARNING: xeroxPhotocopyig fis bookis'a CRIMINAL act, Anyne ful yi LABLE to tace LEGAL for Modifying Structure of Views ‘The ALTER command is used to modify the structure of views : ALTER VIEW viewname “ALTER [COLUMN] columnname SET DEFAULT Default option ‘Example ALTER VIEW Project info ALTER [COLUMN] project name SET DEFAULT “Online Enrollment” y ALTER VIEW view name ‘ALTER [COLUMN] columnname DROP DEFAULT ‘Example 7 ALTER VIEW viewname ALTER (COLUMN) project_loe DROP DEFAULT 1.2 RELATIONAL ALGEBRA - 023, State various fundamental operations in the relational algebra and explain them with suitable examples. (Model Paperstl, 5 | May-13(R08), 3) OR Explain the fundamental operations in relational algebra with examples. (May-19(R16), Q4(a) | April-18(R16), Q4{a) | May-17(R15), Q4(a)) OR With a suitable example explain division operation in relational algebra. (Refer Only Topic: Division) | Anewer May-15(R13), Q4(a) Relational Algebra Relational algebra is a query language, which is used to manipulate the data in the relational data model. The queries in ‘ational algebra are formed using set of operators that accepts atmost two relation instances as arguments and then returns a new instance as the output. This property of composing the queries using operators helps to easily create a complex query. ‘The different operations of relational algebra include, 1. Select 2. Project 4. Set operations 4 Rename 5. Joins & Division. a ih g ter to understand all the operations of relational algebra, consider a COMPANY database that consist of five tables Set as shown below, EMPLOYEE (Ename, Eid, Bdate, Address, Sex, Salary, DNo, Phonenumber, Age) DEPARTMENT (DName, DNo, Manager_id) ‘ DEPT_LOCATION (DNo, DLocation) } PROJECT (PName, PNumber, PLocation, DNo, Eid) DEPENDENT (eid, Dep_Name, Sex, Relationship) SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS , - Sa ee eee ‘The underlined attributes represents the primary Key fr the respect MP Accomplete view of “COMPANY” database, ; EMPLOYEE, ‘ rr ‘Ename Bea Address Ser | lca dot oo ete tee te ee [mee | | Jack | 12348262 _| 12-5-1955 | Chica m_| 55000 mani» | St Green | 12345263 | 20-11-1972 |New York | | 200005), 7 73421317 4 Brown | 12345264 | 28-7-1968 | Chicago m | 40000 [8 | 773210192 2 win | rasasans | s-ai9ss | darn | F_| 350000] 8» | 773271882 a Jal 12345266 | 04-4-1965 ‘New York F 42000. | & ‘TT3291828 4l | Donia | 12345267 | 0281968 | Daron | M | 20000] 9 | 773423145 2 John 12345261 10-8-1965 | New Jersey | M | 25000 | ® 773213218. al John | 12375261 | 10-8-1965 | New jersey | M_| 25000 | 9] 775213218 41 DEPARTMENT DEPT_LOCATION DName DNo | Manager.id |] |DNo| DLocation Administration | 7 | 12345261 Pilg sew ee Research 8 12345265 a = Head quarters | 9 12345267 | 3 Chicago PROJECT Kid "| PNumber | PName PLocation | DNo 12345261 21 Computerization | New York g 12345265 31 Product A. Detroit 8 17345267 41 New benefits Chicago 9 12345263, 51 Soft drinks New Jersey Dl 12345264 6 Reorganization Chicago 8 | 12345262 7 Product B New Jersey | 7 DEPENDENT Eid Dep_Name | Sex | Relationship 12354261 | Nivedita | F Mother 12354262 | Alan M | _ Brother 12354263 | Lizzi | F Sister. 12354267 | Roven’ | F | Daughter 12354265 | Peter | M Fae 12354266 | Kumar | M | Brother 12345267 | Sunny | M 7 , 419) Brigit 95051792 WARNING: xerox/Photocopying of this book isa CRIMINAL act Anyone fcund gully le LABLE to tace LEGAL POO she symbol forthe select operation is 0. This operation is used to seleet particular rows from the two relations which cases the given condition, see © ensinytAblenaMe JEPENDENT Sener This can be read as “select from table DEPENDENT where Sex =F". The following table will be displayed. Projection 1 Eid Relationship 12354261) Nivedita |F | Mother | = 12354263 | Lizzi F | Sister 12354267 | Roven F | Daughter | p60 pen ~ wee O8 +4240 Ate Sore EMPLOYEE, This condition selects the rows from EMPLOYEE which satisfies any one or both of the following conditions, DNo=7 and Address = ‘New Jersey’ OR DNo =8 and Address = ‘Detroit’ Projection 2 Ename| Hid Baste | Address | sex | | DNo [phonemumber Salary Yohn }12345261 | 10-8-1965 | NewJersey | m | 25000 | 7 | rsanszie [ar Bil |12345265 | 25-4-1955 | Detroit F | 35000 | 8 | r7sz7ig42 With select operator, different comparison operators can also be used, <= Less than > ~ Greater than =~ Equal to #— Not equal to $= Less than or equal to 2 > Greater than or equal to ‘Inadition vo these comparison operator, “select” operator can even use booledn operator “not” to negate a condition dy: Hrample Display all the information of projects except those which are located in Chicago. cen «en: PROJECT Proton Sse DATABASE-MANAGEMENT SYSTEMS [J 2 Project (n) ; This operator is used to display the lst of attributes! columns defined inthe relation Re Syntax, enn (table may {or) Y ctu) (table name), Example Display project No, DNo from relation PROJECT, Fie: ne PROJECT) Now only these columns are selected and displayed while ther columns are eliminated from the relation Projection 4 Tos an(EMPLOYEB) This query will display the columns sex and salary from EMPLOYEE. However, it must be noted that the duplicate values are not repeated in the new relation. Only unique tuples are listed. This elimination of duplicate values is called as duplicate elimination, which intrun reduces the redundancy. The following relation will be displayed as, Projection 5 The difference between select and project operators is that, the former operator satisfies commutative property whereas the latter doesn’t satisfies the commutative property. The number of columns returned by the project is always equal to orless than the number of columns in the original relation. It is possible to manipulate the data stored in a table by combining both select and project operators. Example: ifthe user wants to display the ‘emp-id, emp-name, birthdate, salary of all the employees whose age is greaterthan 30, then the expression can be represented as, Tra mame, Bae, Say, Aes Tape» (EMPLOYEE) This will retuim the following relation. WARNING: Xerox/Photocopying of this book is a CRIMINAL acl. Anyone found guilty is LIABLE to face LEGAL, Projection 6 pee [ l ) ce stn [245261] John 10-8-1965, Jack | 12-1955 Green} 20-11-1972 Bill 254-1955 Sil] 0441965 Selection and projection operators are unary o they can be applied to only single relation, 3, Set Operations The following are the different standard set o defined in relational algebra. (@) Union (U) When applied on two relations, it returns all the ‘which are either present in first relation or second relation both the relations It does not return the rows Which has the tuple values. All the rows returned by this operator are ‘One of the cons‘raint of union operator is that both the rel must be “union-compatible”ie., bth the relations must have same number of columns and also these columns must have same domain (type of data being stored in each column), IFA and B are two relations and are union com then union of these two relations is expressed as, AUB ~ Retums uniquely all the tuples of A and Example Considera simple Student] and Student2 relation represent juniors and seniors Student (S1) iudeent (S2) RoutNo | Class | Name s101 x Sodir ae x Dhani 3103 xi nee Slus2 — id. “se Intersection (4) coat hese ‘When applied on two relations, A and B (A -B) it returns all the rows which are common to both * Na opersorirt) this operator can be applied to only those relations that are union compatible. For example if slredeh these relations. is applied to S1 and S2 (above relations) then the result will be an empty relation as nothing is commar $1.982=~empty relation imilar to Ifinterseetion operator (>) is applied on EMPLOYEE relation and Projection 2 ~ the resulting relation will Be sim jon 2 relation as it has only two tuples in common, (@ Set Difference (Minus) This operator is also called as “Minus” operator, If A and B are two relations and are union compatible tha oa retum all the rows which are in A but not in B. Consider, this operator is applied to EMPLOYEE and Projection 2 relations, the resulting relation is, EMPLOYEE and Projection 2 a Ba Bdate Address | Sex no | Phouenumber 12345262 12-5-1955 | Chicago M 55000 7 773313218 12345261 | 10-8-1965 | New Jersey] M | 2500 ] 8 | 773213218 ’ 12345263 | 20-11-1972] New York | M | 20000 | 7 | 773421317 12345264 | 28-7-1968 | Chicago M | 4000 | 8 | 773210192 12345266 | 04-4-1965 | New York | F | 42000 | 8 | 773291828 12345267 | (2-8-1968 | Detroit M | 2000 | 9 | 773423175 12375261 | 10-8-1965 } New Jersey] M | 2500 | 9 | 773213218 (@) Cross-Product (*) _ This operator returns all the tuples of relation A plus all the tuples of relation B. Cross product is denoted as, Ax B—retums the Cartesian product of two relations. The resulting relation will be bigger in size than the two relations. A B Column} Columa2 Column A | Columnal | Column B 1 a a; 1 b . 2 b a, 2 3 © a, 3 b, 1 AtB Ee DATABASE MANAGEMENT SYSTEMS 4 Renaming (p) ‘This operator is used to rename the relation oats or both. The éytax Fr this operator is, (A (old name — new name), B) he Bis the old relation which being renamed as ‘A’. “The list which contains the new names for attributes is call a q a For example, the relation DEPT_LOCATION to DLOCATION and the attributes DNo to D-number and DLocation Lt an be renamed in the following manner, P(DLOCATION (DNo —+ D_number, DLocation > D_L) DEPT_LOCATION). ae 7 Its not compulsory to rename both relation and attributes. It depends on the user and this operator simpl /peesentation) of different relations (with different names and different attributes). The exclusion of both the relation name: and attribute names is meaning less. f x Joins Joins are used to combine the information of two relations which have at least one field in common. It is one of the most important operator of RDBMS. In simple words, a join operation can be defined as a Cartesian product followed by selection or Projection operators. The different forms of join operators are, (@) Conditional join (Meta join 8) (&) Equi-join (©) Natural join (@) Outer joins. (a) Conditional Join (Meta Join 6) This join retums a relation that includes a set of rows from the Cartesian product of two relations A and B such that each ‘Tow satisfies a given condition C. This can be denoted as, Abd i.e., join A and B based on some condition ‘C’. This join operation is same as the Cartesian product performed on two relations followed by a selection operator. Thus, AM B= o(A~B) The application of conditional join on relations EMPLOYEE and DEPT_LOCATION results into a new relation consisting of 11 fields. Example EMPLOYEE 4 - DEPT_LOCATION This statement means, j The relation EMPLOYEE and DEPT LOCATION are joined based on the condition DNo>7. The resulting relation include all the tuples from EMPLOYEE and dept_ LOCATION where DNo.>7. TDI Trams Tmnsr Transee Tronsse Tra91828 Tr291628 Trapias TRABIIS WARNING: Xerox/Photocopying ofthis book is @ CRIMINAL dick Anyone found aut) is IABLE to fave LEGAL * — 0 ~ gsi issae ws codons! join, the only difference oin ses equity ‘= operatr to jin the two gta “For example one may join DEPARTMENT and eae ocTION relation with the condition that, 1 Department DNo2.Dept_location, Where DNol rectwoinstances of respective relations. This condition apps re DNo! ~ DNod, The degree of suing jars ge the Sum of degrees of two relation minus the at elds they have is common. More precisely, the resulting relation (Projection 8) DEPARTMENT Pageisenenatkr = Dns DEF. n0caTON DEPT_LOCATION cami all he fields of DEPARTMENT AND DEPT_ JocaTIONand the common: fields will be included only once. rejection 8 Name Administration New York Research Detroit Head Quarters fd PAL Chicago} fo Natural Join This is default join operation i.e., no condition is ‘Natural join is equivalent to Cartesian pro Zrasonshave a common field then the application of natural Fins equivalent o equi join and if no field is common then erat join is Cartesian product of the two relations, duct IFtwo ‘his operation can be denoted as,, ADAB where A and B are two relations natural join operation is applied on DEPARTMENT tuk DEPTLOCATION then the result wll be same as Projection & as they have only DNo field in common. (® Outer Joins ‘Outerjoins are the special variant of “join” operation that are ‘épendenton NULL values. Generally, a ‘join’ operation performs the cross product of two tables and apply certain join condition. Theit select those rows from the cross product that satisfies the ‘Bren condition, But with outer joins, DBMS allows the user to ‘ekctbose rows which are common satisfies the given) and even ters that does not satisfies the given condition. Project PL PNo | Pname 44 D A conditi @ FROM 1 DI, Project PI wane DI PNo=P1LPNo: as follows, imple join ected that sts include rows that does not OUTER JOINS can be used. s of outer joins namely, This tables shows the si where only those rows are s€ However, inorder t0 i ion, the concept o ‘There are three tyPes @ Left outer join Right outer join ii) Full outer join. Left Outer Join . ‘ ef outer join list all those rows which are commas to both the tables along with the unmatched rows of the second table are, Example SELECT * DI.* PI FROM Department D1, LEFT OUTE! WHERE D1_PNo = P1.PNo; The result of this statement is as follows, R JOIN Project P1 = pt_Mid | DNo | PNo_| PNo | Pname | De ! ! L A B NULL im 2 33 il 2 NULL | 101 7 120. ai So, the left outer join resulted in a relation that have ‘common rows from both the tables and also the row which ‘does not have match in the other table. The values of the attributes corresponding to second table are NULL values. Right Outer Join Right outer join is same a8 the left outer join but the only difference is the unmatched rows of second table (specified on the right hand side) are listed along’ with the common rows of both the tables. SELECT *.D1,*P1 FROM Department D1 RIGHT OUTER JOIN Project PI WHERE D1.PNo = P1.PNo; Dept_Mid| DNo | PNo | PNo | Pname NULL |NULL] NULL | 44 D 101 2 u W A 97 5 |2 2 c ‘The values of attributes for the first table are declared as ‘DATABASE MANAG! (ii) Full Outer Join This is same as the right outer joi i n ight outer join and left outer join Putenly ference is unmatched rows ofboth tables are sted along with the common rows of the tables, SELECT *.D1, * PI FROM Department D1, FULL OUTER JOIN Project P2 WHERE D1.PNo=P1.PNo; : The following table shows the result,” Dept_Mid] DNo | PNo | PNo | Pname 101 2 W W A 7 Sih 2 B | 120 4 33 NULL. NULL NULL | NULL] NULL 4 D In this relation all the matched and unmatched columns, of both the table are displayed, the values for the unmatched attributes are entered as NULL, 6 Division Consider two relations P and Q such that P contains two attributes ‘a" and ‘6 and Q contains only one attribute “ The attribute “bin Q has similar domain as that of P. Thus the division operation represented as P/Q, can be defined as the set ofall values of ‘a’,wherein each value of *h’ in Q has a tuple in P. Assume that for a set of “b' values in P there exists a corresponding set of ‘a’ values in P. Thus, the value ‘a’ is said to occur in the result of P/Q if the set of values of ‘6’ in P has all the values of *8”in Q. Consider the following relations, EMPLOYEE(EName, Eid, BDate, Address, Sex, Salary, DNo, Phonenumber, Age) DEPARTMENT(DName, DNo, Mantager_id) PROJECT(PName, PNumber, PLocation, DNo, Eid) Expression Find the names of the employees who handles projects belonging to all departments named ‘Head-quarters’ The use of the word ‘all’ suggests that the division operator ‘can be used. The query for the above SQL expression is, PT opcier apne PROIECT (Mon (Siam » ts que DEPARTMENT))) Tosa Tggeis PAEMPLOYEE) Consider a temporary relation T,,.., which is defined by using the division operator. The relation eyaluates the set of Eids belonging to the EMPLOYEE relation. These Eids are those who handle project in every department named “Head quarters’. The PROJECT relation has Eid and DNo schema and the DEPARTMENT has DNo and DName schema. Thus, when WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL | MENT SYSTEMS [J Fenton operator applied all the ids are returned such tha i a PPARIMENT, heres acorn “Eid, DNo> in the PROJECT relation. Here, a selection (g penton is applied on DEPARTMENT s0 as to compute telonging tothe DName ‘Head quarters’. This result na vay 9, For the DNo ‘9°, there is a corresponding 1212345267, 9> in the PROJECT relation. Thus, T.,., <12345267, 9>, When T,,,. is combined with EMPLOYEE using the join operation, EName corresponding to <1234526 ‘9 is evaluated, which is ‘Donald’, In RDBMS, the division operator is applicable only 4 some types of queries. The usage of division operator is v less. The division operator can’t be used alone in datab 25000} 1N is the tuple variable which is created for every tuple tuples which are evaluated to true are displayed ‘ General Rules for TRC Queries ~ ‘The general form of any tuple relational calculus query is, and the condition N salary > 25000 is applied to each tuple. All) {A App Ashe Aphy TP Ay AAs Ad) 4, The value of ‘m’ is always greater than or equal 10 value of “n” & — AyA,,A, forms the set of tuple variables. Ky Xy Aer, ae the attributes of relations 4 Fiscalled as formula or well formed formula (wl) which is made up of atoms. A formula is said tobe js in one of the following form. WARNING: Xerox/Photocopying of this Book is b CRIMINAL act: Anyone found gully is LIABLE to face LEGAL to Relational Model, Relational Algebra 19 where R represents a relation and A, represents a uple arable a GX OPA, %, where A, and A, are tuple vatiabl ich the formula is evaluated to either true ee Nua (Opconstant oF constant Op A,x, where A, and A, are tuple variab the help of atoms, formulas can be defined by using following rules. Eyery atom is a formula FP, and F, are two formulas, then F,ANDF, FORF, NOT F, are also formulae. i | ‘The formula make use of the two quantities namely, ‘is universal quantifier: (Vx) (R) This means, forall the values of x the formula R evaluates to true. | isa existential quantifier : (3x) (R) —This means, there exist some value (at least one) of x for Which the formula __ Revaluates to true. j “The variable °x' is said to be bound because itis attached to one of the quantifiers. The variables are said to be free if they -genotattached t0 any of the quantifiers. The free variables always appear at left hand side of a bar (|) of a query expression. sample Find the names and ages of the employees whose salary is greater than 25000. _ {A|3N € EMPLOYEE (N.salary > 25000. A.Ename = N. Ename » A.Age = N.Age) Here, ‘A’ is a free variable (tuple variable) with two fields name and age."‘N’ is bound to quantities (2). This means there aristsome employees whose salary is greater than 25000, The above equery list the name and age of such employees. 4 — Thefinal rule is, 3x (F) and V x (F) are formulas if Fis a formula @ with a free va 1. Domain Relational Calculus (DRC) ble x. DRC is similar to TRC but the only difference is DRC make use of domain variables instead of tuple variable. Domain vari- ables are those variables which are defined for the domain value of the attributes. For example the attribute ‘age’ is a tuple variable ‘hich take the tuple values from the relation but when it comes to DRC ~ the attribute ‘age’ will take the values from its domain — int, ‘QBE (Query-by-example) isa language which makes use of DRC where as SQL (Structured-query language) is based on TRC. The general form of DRC query is, : (5-25) | F(a ay ay. ,))} Where a,,a,,a,..... a, are domain variables and F(a, a,. a... )) represents the DRC formula. The result of a DRC Mery is set of all tuples for which F(a, a,, a.) evaluates to true. The formula F((a,,@,y a,..., &,)) consist of atoms — and ‘ach atom is defined as, @ R(a,a,,a,,,...,9,) where R represents a relation and a,,a,;a,.... a, represents domain variable. {b) a, op a, where a, and a, are domain variables and op represents set of comparison operators (>, <=, #, 2, <) {©) a, op constant or constant op a, where a,, a, are domain variables and “Constant” is a constant variable from the domains of a, and a, respectively. {@) Asin TRC, we can build the formulae is DRC as well with the repeated use of atoms by applying the following rules, 4% Every atom is a formula % IfFI and F2 are two formula, then F, ANDF,, FOR, NOT F,, are also formulae, @ IfX is a domain variable of formula F, then 3x (F) and v x(F) are also formulae ‘ | SPECTRGH @LLAT-ONE JOURNAL FOR ENGINEERING STUDENTS | 9) ad isa non-procedural or declarative language. allows the programmer to specify what data is to be retrieved but not the way o the way ita ay of THis a procedural language. Irallows the programmer fo specify what data is required and also the way of retrieving it Tis possible to express all relational algebra Itis restricted to safe queries on the calculus. {queries into relational calculus, Itis mostly preferred by the end users. It is superior than relational algebra Its considered as a user-friendly language The level of abstraction is high. The implementation of relational calculus is ‘more efficient. It determines the order of evaluation based on the compiler or interpreter. It is difficult to learn. Itis mostly preferred by the programmers. Itis inferior than relational calculus. Its not considers a user-friendly language. The level of abstraction is low. The implementation of relational algebra is less efficient, It determines the order of evaluation by itself Tris easy to learn. The queries are represented in a logical form The queries are represented in an algebraic form. It defines a relation in terms of one of more It defines a process of building a relation from one relations, ‘or more relations. Q29. Let R = (ABC) and S = (DEF) let r(R) and s(S) both relations on schema R and S. Give an expression the Tuple relational calculus that is equivalent to each of the following. é () oy lt) (i), (o2,,(r* 8) (il) rns Answer: ~ May-17(R15), 0 Given R = (ABC) and S = (DEF) such that r(R) and s(S) are relations on schema R and S. Then, () Expression in the domain relational calculus that is equivalent to, Gf?) is {er 0 1B] = 19} (ii) Expression in the domain relational calculus that is equivalent to, pid} A (€F1 = afl « pICl = 4D} (iii) _ Expression in the domain relational calculus that is equivalent to, T1,(o,_(e*s))is (t|3peraqes (tld! Q30. Write the following queries in tuple relational calculus for following schema, Sailors (sid: integer, sname: string, rating: integer, age: real) Boats (bid: integer, bname: string, color: string) Reserves (sid: integer, bid: integer, day: date) (i) Find the names of sailors who have reserved a red boat. (il) Find the names of sailors who have reserved at least one boat, (i) Find the names of sailors who have reserved at least two boats. {iv) Find the names of sailors who have reserved all boats. ‘Apri, Set Answer = al S.sid * B.bname = S.sname \ 3 B Boats (B.bid = R.bid » B.color= a {TASE Sailors 3 R € Reserves (R.si (i) (T/3Se Sailors 3Re Reserves 3 Be Bouts (Ssid= Rid Bane =§sname)} (/ASe Sails 3R, € ReseresR,€ Reserves 3Be Boss Ssit=R, sR sil=R.sidR bide bid Be (1/S € Sailors VB €Boats (2 € Reserves (Sssid = Rsid » R.bid = B bid » B.bname = S.sname))) (iii) (iv) WARNING: xerouPholocoing of ibook CRIMINAL act Anyone ound uiyis LABLE to face LEGAL prom luction to Relational Model, Relational Algebra Formulate an expres Wout) (itl) reg i Nee y \F(Foaol . May 49(R16), 0548) in the tuple relational calculus eins that is equivalent to I1,(¢) is, @ o0 __Bapresson in the tuple relational calculus that is equivalent to 0, _() is frer* l= 17) a ans “Expression inthe tuple relational calculus that is equivalent to» ss, lB € 734 € (614) = pl] 4 8) = p{B] » 1(C] = p[C] A fD] = gl] » HE] = gE) a AF) = aE} fi) Mylop.9(t <8) ‘For answer refer Unit-Il, Q29(ii). EZ Consider the following schema to write queries in domain relational calculus, ‘Sailor(sid, sname, age, rating) Boats(bid, bname, bcolor) Reserves(sid, bid, day) |) Find the boats reserved by sailor with id 567. 0) Find the names of the sailors who reserved ‘red’ boats. {¢) Find the boats which have at least two reservations by different sailors. Answer @ {0641 T, A(1,N, T, A> € Sailors » 3< Ir, Br, D> € Resource (Br = Ir 41 = 567))} ®) (NPAI,T, A( € Sailors ~ 3 <1, Br, D> € Reserves 4 3 € Boats)} 19 (@NPG1,T, A(<1,N, T, A> 3 Brl, Br2, D1, D2(€ Reserves A ~ I, Br2, D2 > € Reserves 4 Bri + Br2))} EXERCISE QUESTIONS * ‘Consider the following schema, ‘Student| 1D | Name | Major | (Major —Foreign key) we Course | Dept | Name | Title | (Dept~Foreign key) Det Abbrev| Name | Office rer » SID Dept | Num | Date | (SID- Foreign key, Dept, Num — Foreign key) the following queries in domain relational calculus for following schema, May-15(R13), 5 u lors (sid; integer, sname: string, rating: integer, age: real) S (bid: integer, bname: string, color: string) (sid: integer, bid: integer, day: date) ‘pa J ed Red boat the names of the sailors who have reserv the boats reserved by sailor with id 115. all the ids of boats that are reserved. s the key difference between primary key and foreign key? SPECTRUM ALLIN-ONE JOURNAL FOR ENGINEERING STUDENTS ane a DATABASE MANAGEMENT SYSTEMS LINTUSHYDE Ry, neh nL Co) MOL (0) ‘to brit notes on sitering tables and views. Ate! For anewer refer Unit, QS “ay 4118), 1) | May-1(R13), 6) G2 Define the terms primary hay conataine and foreign hay and check constraints. ‘Ate For answer refer Unie, Q3 foe SOIMSY Ry Q3. What are Joins? List the four different Join operators. Ate! For answer refer Unit, Q9. \ Important Ou ESSAY QUESTIONS Q4. Explain the fundamental ‘operations in relational algebra with examples. (May-19(R16), Q4(a) | April-18(R16), Q44a) | 023. 5 May-47(R15), Ma) May-15(R13). 4) | May-13(R09), 23) QS. What is a relational calculus? Explain in detail Tuple Relational Calculus (TRC) and Pomain Relational Calculus (ORC) with example: Fay Ams: For answer refer Unit Ey Ams: For answer refer Unit-Il, Q27 (May-16(R13), 04 | May-16(R313), 05) 6. What are the SQL. construct to modify the sinus of tables and desire tablee aod views? Ans: For answer refer Unit-II, 022. (NowsDec.-18(R16), 23(b) | April/May-12, Set-1, Q3(b)) Q7. Explain briefly integrity constraints over relations. ey fs Ams: For answer refer Unit-ll, Q16. (May-19(R16), Q3(a)| AprivMay-12, Set2, a3(0)) fH TIMES) Q8. Define the terms relational model, relation ‘schema, relation instance, relational database schema, main constraints, cardinality of a relation, degree of a relation. Ams: _For answer refer Unit-Il, Q12. Important 28. What is relation? Differentiate between a relation schema and relation instance define the term u and degree of a relation? What are domain constraints? Ans: For answer refer Unit-Il, Q13 (important Question | May-17(R15), 210. Explain logical database design in detail. Ans: For answer refer Unit-II, Q19, Important 11. Database systems use some variant of relational algebra to represent Query evaluation plans, why, algebra is suitable for this purpose. ‘Ans: For answer refer Unit-II, Q25 {important Question | Apri-1t, Set 12. Let R = (ABC) and S = (DEF) let r(R) and s(S) both relations on schema R and 8. Formulate an sion in the Tuple relational calculus that is equivalent to each of the following, ME i) og) il) FS iv) TA fo. fr 8). Ans: For answer refer Unit-II, Q31 (important Question | May- WARNING: Xerox/Photocopying ofthis book isa CRIMINAL at! Anyone Yound gut 6 LABLE to face LEGAL proceedings.

You might also like