You are on page 1of 56
{Syllabus GOL: Queries, Constraints, Triggers: Form of Basic SQL Query, UNION, INTERSECT ond EXCEPT, Nested Queries, ‘Aggregation Operators, NULL Values, Complex Integrity Constraints in SGI, Triggers and Active Data Bases: ‘Schema Refinement: Problems Caused by Redundancy, Decompositions, Problems Related to Decomposition, Reasoning about Functional Dependencies, FIRST, SECOND, THIRD Normal Forms, BCNF, Lossless Join Decomposition, Multi-valved Dependencies, FOURTH Normal Form, FIFTH Normol Form LEARNING OBJECTIVES The Concept of SQL and SQL Queries Basic Structure of SQL Query Types of Database Languages Various DDL and DML Commands Concept of Triggers and Active Databases Introduction to Schema Refinement Redundancy and Decomposition Introduction to Normalization Various Normal Forms such as INF, 2NF, 3NF, BCNF, 4NF and SNF. INTRODUCTION SQL (Structired Query Language) is a database language that enables programmers to write queries for accessing database. The S@L data definition language creates, alters and deletes the relations in a database. The additional basic operations and set operations, null values simplify the presentation of different relations. The Aggregate operators improve the data retrieval property of SQL statement, 15000); ‘The above statement returns a value for the column containing employee's salary greater than 15000, (i) NOTIN: The negated version of IN operator is NOT IN. It retums a true value if an element is not in the given Set. Otherwise, returns a false value Example: SELECT E,ename FROM Employee E WHERE E.eid NOT IN (SELECT D.Dept_managerid FROM Department D WHERE D.DNo=6); The above statement returns a value true for the row that Contain the names of employees who are not working in number 6, 85 4. What is meant by nested queries? 7 A é May-16(R13), a1(4) Nested Queries 2 ‘A query inside a query is called as nested query. Inner query is called as sub query. Sub query is usually present in WHERE or HAVING clause. In other words the main query that contains the subquery is called as nested query. Example Find the names of employees who are working in department number 6. Solution SELECT E-Ename FROM WHERE Employee E Bid IN (SELECT D.Dept_Managerid FROM Department D WHERE D.DNo = 6); Q5. What are aggregate operators? List the different types of aggregate operators. OR Write down the various aggregate operators, of SQL. Answer : Now Dec. 18(R16), a1(d) Aggregate operators (functions) improves the data retrieval property of SQL statement. These operators enables the users to summarize the data retrieved from the relations. Basically, the aggregate operators takes the entire column’of data as its argument and generates @ result set that summarizes the column. The following are the different aggregate operators, supported by SQL The following are the different aggregate operators supported by SQL, COUNT: COUNT followed by a column name returns the number of tuples in the specified column, 2, SUM: SUM followed by acolumn name retums the sum. of all the values in the specified column. AVG: AVG followed by a column name returns the average value of all the values in the specified column, 4. MAX: MAX followed by a column name returns the ‘maximum value from the values present in the specified column. 5. MIN: MIN followed by a column name returns the minimum value from the values present in the specified column, .... SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS a Q6, Define Trigger and give an example. ‘Answer : Nov/Dec. -18(R16), a1(¢) ‘Triggers AA trigger can be defined as a program that is executed ‘by DBMS whenever updations are specified on the database tables. More precisely, it slike an event which occurs whenever a change is done to the tables or columns of the tables, Only DBA can specify triggers, Example Consider the following trigger description wherein the trigger “emp-count” counts the number of employees inserted. CREATE TRIGGER emp-count BEFORE INSERT ON EMPLOYEE /* Event */ DECLARE (Count INTEGER BEGIN ie asia sh Comt:=0 END" ‘This example clearly explains that the trigger must be ‘activated before each insertion into the employee table and the action to be taken whenever an insertion is made. Q7. Whatis an active database? Answer : May-15(R13), Q4(d) Active database is a database consisting of set of triggers. These databases are very difficult to be maintained because of the complexity that arises in understanding the effect of these triggers. In such database, DBMS initially verifies whether the particular trigger specified in the statement (that modifies the database) is activated or not, prior to executing the statement. If the trigger is active then DBMS executes the condition part and then executes the action part only if the specified condition is evaluated to true. It is possible to activate more than one trigger within a single statement. In such situation, DBMS processes ‘each of the trigger randomly. The execution of an action part of a trigger may either activate other triggers or the same trigger that initialized this action. Such types of trigger that activates itself is called as ‘recursive trigger’. The DBMS executes such chains of trigger in some pre-defined manner but it effects the mncept of understanding the collection of triggs Q8. What is schema refinement? Answer : ‘Aprit-49(R16), Q4(0) Schema refinement is a process of refining the schema 80 as to solve the problems caused by redundantly storing the information. Redundancy in its simplest terms can be defined as duplication of data, which is the main cause forall the problems that exists in database, One way to eliminate the redundant data is to make use of decomposition which is the process of breaking longer relation into smaller relation schemes. This division into smaller schemes is based on the functional and other dependencies which are specified by the database designer. WARNING: Xerox/Photocopying ofthis book is a CRIMINAL act. Anyone found guilty is LIABLE to face. duplication of data, which is uit a database, If modiicat ee data, then it is necessary to perform the s multiple fields of database. Decomposition a ‘Decomposition is the solution to the problem ‘eans breaking up the large scl smaller multiple schemas. Ithelps to remove all the: and also helps to maintain data integr Q10. Explain what are the problems dundancy. Answer : ‘The problems caused by redundaney are, Anomalous Updation If update operation is performed, for €x Emp_Section_Id 268 is updated to 520 and this made only to the first record of the database, then lead to inconsistent data, unless all the copies in th are updated. This is referred as update anomalies. Th ‘must be done to all the copies of data, di) th @ Anomalous Deletion Delete anomalies refer to the ‘condition impossible to delete some information without loosi other information. For example, deletion of grade Emp_Section_Id 268, (ii) Anomalous Insertion a Insertion anomalies réfer to the condition where it compulsory to store some information in addition to some. information. For example, if a new employee record is b entered, who has not yet assigned an Emp id, and an ass is made thatthe null values are not allowed, then it to enter the new record unless the new empl assigned an Emp_d. This is called as ae Q11. Explain transitive dependency with an Answer : ‘Transitive Dependency The functional dependency X—> Yand ¥—>Z: be transitive dependency if there exist a functional XZ vinattribute ¥. ie Example FDI : Student Id —> Course_Id FD2 : Course.Id—> Fee » FD3.; Stdent_Id > Fee The functional dependency FD3:is dependent. ' UNIT-3. SQL and Schema Refinement {@12, What is normalization? What are the conditions roquired for a relation to be in (NF, 2NF? Answer! Normalization ‘Normalization is the process of converting a relation toa standard form by decomposing a larger relation into simaler efficient relations that depicts a good database design Nommalization technique involves a sequence of rules that are ‘employed to fest individual relations so that the database can ‘penormalized to any degree, The main objective of rormaliza- tion isto refine the design of database in order to remove data maintaining anomalies, reduce data redundancy and to eliminate data inconsistency, Conditions to INF Arrelation schema is said to be in first normal form if the attribute values in the relation are atomic ic.,'there should fe no repeated values in a particular column Condition ‘A relation is said to be in 2NF, if the following two conditions are satisfied, (Model Papert, a1(6)| May-19(R18), a) to 2NF () —Arelation must be in INF (ii) Andn-key attribute must be fully functionally de ‘on primary key Q13, List the advantages of nomalized relations over unnormalized relations. Answer + lent “The advantages of normalized relations over unnormal- {ued relations are (i) Normalized relations (tables) does not contain repeating ‘groups whereas, unnormalized relation (table) contains ‘one oF more repeating groups. (ii) Normalized relation consists of a primary key while there is no primary key in unnormalized relation (ii) Normalization removes the repeating group which occurs many times in a table, iv) With the help of normalization process it is possible to {ransform unnormalized table to first normal form (INF) by removing repeating groups from unnormalized tables. () Normalized relations (tables) gives the more simplified ‘esult whereas unnormalized relation gives more compli- cated results (i) Nonmalized relations bring progress in storage efficiency, ‘data integrity and scalability. But unnormalized relations ‘cannot improve the storage efficiency and data integrity ‘Normalization results in database consistency, flexible data accesses, tg it SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS 87 Q14, What is second normal form? — May-16Rt2, a4) oR sue Define SECOND normal form. Answer ay R19, ON)” Second Normal Form (2NF) A relation is said to be in 2NF if it isin INP and every. non-key attribute is fully fumctionally dependent on primary key attribute. A relation is said to be in 2NF if any one of the following conditions are satisfied. 1. There should be only one attribute associated with the primary key. 2, There must be no non-key attributes in the relation. Non-key attribute must be functionally dependent on the set of primary key attributes ie., partial dependencies must not Example ‘Consider a simple example of STUDENT relation. Student (Student Id, Class_Id, Name, Course, Time) Clas ) isthe primary ke: Q15. Define BCNF. Write down its basic properties. " NoviDee-10(R16), 10) relation schema R is said to be in BCNF ifthe following. statements are true for each FD P > Q in a set F of FDs that hold over R. Here, P is the subset of attributes of R and Q is a single attribute of R Answer : (i) The given FD isa trivial, 4e,, QEP (ii) Pisa super key A tuple in a BCNF relation is considered as an entity or ‘relationship, described by attributes other than the key. The key is used to differentiate each tuple. The structure of such a BCNF relation R can be obtained ‘by representing the attributes of R as square boxes and drawing ares between the key and the attributes to indicate its FDs. PDs iE “0 @ be me Key: Super key, Ay Ayy 4,‘ Non-key attributes, Figure: Structure of BCMF Relation Indicating its FO BCNF is considered fo be the most desirable normal form with respect to redundancy, since itrestricts the detection, of redundancy using only the FD information. i 88 DATABASE MANAGEMENT SYSTEMS [JNTU-HYDERap,,, “ane O16. What is the difference between INF and BCNF? (Model Papert O10 | Maro, Answer : : om — = i a Ifa functional dependency A — B is present, then Ne ‘allows this dependency to be in a relation if and only if, ‘B’ isa primary key attribute and ‘4” is not a candidate key, Arelation in 3NF need not be in BCNF. Wa functional dependency A —> Bis present, then BCNF allows this dependency in a relation only if ‘A’ is a candidate key. Arelation in BCNF is also in 3NF. " Decomposition of BCNF relations is not possible, Itis possible to decompose any relational schema into set of 3NE relations, by using decompositions that possess certain desirable properties like lossless- join, dependency preservation. BCNF guarantees that no redundancy can occur using only the information about functional te dependencies. ‘Theres a possibility of some redundancy to occur because every transitive dependency is not eliminated. G17. Define lossless join decomposition with example. Answer : Losstess-join Decomposition Example Consider a relation, R(M, N, 0) and it is decomposed into two subrelations R, Lo ra (M,N) and RN, 0). M TPR Piel ps lime R(M, N, 0) a R(M,N,0) = RM,N) RW, 0) That is, R(M,N) => S Fy To] RAN.) = : 2 2 wlafrfs WARNING: XerouPhotocoping ol his Book's @ CRIMINAL SAR and gui LIABLE face LEGAL proceedings ‘The condition for lossless decomposition should be, Re R=R Here, the R, > R, returns R Theabove ition is lossless join decom, 018. Mention the properties of decomposition. Answer # Nov /Dec.-18(R16), A1(0) ‘The two properties of decomposition are as follows, Lossless-Join Property This property helps to identify any instance of the eriginal relation from the corresponding instance of the smaller elation attained after decomposition. , (o) Dependency Preservation This property helps to enforce constraint on smaller relation in order to enforce the constraints on the original ‘relation. To answer the second question a number of normal forms cists Every relation schema isin one of these normal forms and these normal forms can help to decide whether to decompose the relation schema further or not. One ofthe drawbacks of decomposition is that it enforces tojain the decomposed relations in order to solve the queries ‘of the original relation. This may result in the performance degradation if such queries are common. In order to improve the performance it is necessary to ignore the problems caused ty redundancy and decomposition of the relation. Q18. Define Multivalued dependencies and joi dependency. April-18(R16), QUA) sition. « OR Write about join dependencies. May-15(R13), a1(f) Multvalued Dependencies MVDs are generalization of functional dependencies. They can be represented as, Course —>—> Student . Course —>—> Text book + This is read as “student is multi-dependent on course” "Course multi-determines Textbook”. ‘The meaning of MVD Course —>——» Student is, ‘There exists a set of students corresponding to each She Cie, fora colrse Cand a textbook, B, the set of students } halite air (C8) in CST depends on the value of C only. ke eet ofthe value B. A multivalued dependency can as: IEX,Y,Z are the atribute sub sets of attribute set of tage HP is nid to be multi-dependent on X if for every ‘of A, a set of Y values matching a given pair (Xvalue, lu) Ml, pends only on the X value and does not depend on Z Dependency Ajoin dependency refers to a constraint that is provided i base sctiema. For instance, on. group of relations over a database schema. For iting table 'S*holds a join dependency relationship if multiple tables consisting of similar attributes of" are joined so as ta reereale the table S. Let M,, My . to a relation M. Here, M is said to have a jom n relationship i., °(M,, My’ M.A) if the following equation satisfies for each relation m of the schema M. MyM, be a group of relations coresponding m= eq ( PH) PAM 9M) OI Mg A) ,,(m) Join dependency is said to be trivial if and only if any of the relations M,, M,, M,...M, contain all the attributes of the relation schema M. 20. Describe the inclusion dependencies (Model Papert, Q4(f) | May-16(R13), Q1(N) Answer : Inclusion dependency isa statement containing attributes a A and B in X and Y relations respectively such that 4 is dependent attribute and is a subset of B which is its referenced attribute, Foreign key constraint which allows columns in one relation to refer the columns ofa primary key is an example of inclusion dependency. 3.1 SQL: QUERIES, CONSTRAINTS, TRIGGERS 3.1.1 Form of Basic SQL Query Q21. What is SQL? List the features of SQL. Answer : SQL 4, SOL (Strctared Query language) a database language whichis compatible with RDBMS. It provides an simple relational database. It is a simple portable language that does not require enough learning to work with its ‘commands. It performs the following functions, (8) Creates tables and database structures, (©) Performs addition, deletion and modification operations on the database structures. (©) Performs dificult queries to convert raw data into useful information. t Al these operations are performed using the concept of DML (Data Manipulation Language) and DDL (Data Language). Features of SQL 1. SQLs a nop-procedural and English-like language containing statements in English sentences. Hence SQL are easily understandable. ‘It minimizes the time required in creating and maintaining the database systems It isa portable language and can be executed on various computer systems. It gives quick solutions to complex queties. It enables communication between clients and servers over a network. It is also an interactive query language that allows users to store data on adhoc bases. sarees It enables programmers to write applications for accessing database. 22. Explain about the basic form of a SQL queries. Answer : Basic Form of SQL Query The basic structure of an SQL query is, SELECT [DISTINCT|ALL] Column-list FROM TABLE-list WHERE condition; ‘The above structure of an SQL query consists of following three clauses, @ SELECT (i) FROM (iii), WHERE. () SELECT Clause SELECT clause is used to query data from a relation present in a database. The result after executing the SELEC™ is another relation which is derived from the relations specified. The resultant relation consists of list of columns that to be in the result of a query, = SELECT clause can be followed by two optional keywords DISTINCT or ALL. If the keyword DISTINCT 4 with the SELECT clause, then the resultant relation doesn’t contain any duplicate rows, On the other hand, if keyw used; then it specifies that duplicate rows are eliminated from the resultant relation. Generally, asterisk ‘denote “all attributes” ofa relation, This clause may even include arithmetic expressions that consists of ari (4,~, %/) that are operating on constant or attributes of tuples. WARNING: Xerox/Photocopying ofthis book is a CRIMINAL ct: Anyone found guy is LABLE to face LEGAL UNIT-3: SQL and sq Ga (i) FROM Clause Q23, What are the types of languages a database FROM clause specifies the list Of relations that are to ER ee eee be seanned during the evaluation process s0 a8 to retrieve the 8 bas 8 ao t co Is he Cartesian product operation Give an overview of database languages ~ DDL inarel Algebra, Itis followed by table lst t the lis oftable names ffom which data iso be relent rr pai, 40 R16), 03a) table list can in tur be followed by a range variable when the | ABSWEF # any same table-name is used more than once in the table-tst, Database Languages (ii) | WHERE Clause WHERE clause is used to ‘Specify a condition (s) based con which the resultant relation is derived. Ths relation contains only those rows that satisfy the given condition, SQL uses logical connectives as well as comparison operators in the WHERE clause. The operand of logical connectives are the expressions consisting of comparison operators Examples Consider the following schema, Employee(Ename, Eid, Esal, Phone, Age, DNo) Department(Dname, DNo, Dept. Managerid) Project(PNo, Phame, Pduration, Plocation) Query 1 Find distinct names of employee SELECT DISTINCT Fname FROM Employee: Query 2 Find all the employees who are working in department number 7, SELECT * FROM Employee E, Department D WHERE D.DNo = 7; Query 3 Find the names of employees who are working under Project-number 44 and project-location is either Hyderabad or Bombay, SELECT E.Ename, D,DNo, PPlocation, P.PNo FROM Employee E, Department D, Project P WHERE E.Eid = D.Dept_Managerid AND. PPNo= 44 AND (PDiocation = ‘Hyderabad") OR (PPlocation = ‘Bombay’); hae ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS ‘The database languages are called sublanguages. This is because they do not have all the facilities of a full-fledged programming languages. Several constructs like selection and iterative statements are not available. The sublanguage has two parts, 1 Data Definition Language (DDL) 2, Data Manipulation Language (DML). DATABASE LANGUAGE. DATA DEFINITION LANGUAGE DATA MANIPULATION, LANGUAGE, Data definition language is used for designing database schema, Data manipulation languages are used for queries and operations like insertions, deletions ete, 1. Data Definition Language (DDL) Data definition language defines the schema for the da~ tabase by specifying entities and the relationship among them. It also says some security constraints The execution of DDL statements results in new tables, These tables are stored in “system catalog” also called data dictionary Data dictionary has the information of all the definitions of database schema, low-level data structures, files and records, It also maintains the relationship information among Various records. Data dictionary provides faster access to, database by maintaining certain indexes. Data dictionary also contains meta data that has data about the data stored in database. Data definition language allows the \iser to specify the storage and access methods by using a special language called data storage and definition language. » 2. Data Manipulation Language (DML) Data manipulation language performs the following operations, (i) _ Insertion of new data (ii) Deletion of stored data (iii) Retrieval of stored data (iv) Modifying the data, A CC SAO Ul . DATABASE MANAGEMENT ‘SY! ‘STEMS {JNTU-HY{ Data manipulations are applied at intemal, conceptual and external databases, However, the level of complexity in- volved varies. Complex low-level procedures allow efficient access, but external procedures focus on ease of | usage, there by incurring low complexity, v ‘Data manipulation language that involves in retrieval of| called “query language”. DML are classified based, on Tetrieval constructs. data is the DATA MANIPULATION LANGUAGE fof sane: tosint ean [Pocmumroe] —[Rovrnocenamcian Figure: Classification of DML (a) Procedural DMLs Using procedural DML the user can specify what data needs to be retrieved, The user also have to guide as how to retrieve the data, This means that the user has to express the operations that would retrieve the desired data, DML initiates by evaluating these operations. The result of evaluation is again operated until the desired data,is retrieved. The DML statements are embedded into high-level languages to perform selective and iterative operations, (>) Non-procedural DMLs Non-procedural languages are also calléd declarative languages. These languages are easy to lear’ as the user simply needs to express the desired data. It is up to the database system to choose an optimal procedure to retrieve the data. DBMS translates the DML statements into set of procedures and retrieves the data SQL (Structured Query Language) and QBE (Query By Example) are some of examples of non-procedi Q24. Define data manipulation. Explain commands used in data manipulation. OR Explain various DML function in SQL with examples. Answer : May-19(816), a5(0) Data Manipulation Data manipulation is a method of manipulating data 6n ‘database using various operation. It uses DML. for this purpose. DML ‘The Data Manipulation Language (DML) uses the following commands to perform operations in databases, 1. SELECT command INSERT command UPDATE command DELETE command, oi SELECT Command ‘ ‘command i used in SQL queries, at the basic ea which is used to re in ‘or to select specific columns from the Hay NL query starts with the SELECT keyword ease thelist of columns that forms the resulting re aol asic format of SQL query is, SELECT _ select_list FROMf from list WHERE condition; Example SELECT Ename, Eid FROM Employee WHERE Esal > 20000; FROM Clause This clause specifies the names of the tables from data is to be retrieved. FROM is followed by a range values which uniquely identifies a table, name occurs more than once. WHERE Clause WHERE keyword is used to specify a condition. All tuples which satisfy the condition are selected. The various other clauses that can be used in the SEEE statement are GROUP BY, HAVING, ORDER BY et GROUP BY Clause (a) ) © GROUP BY clause is used to group the data ofa tf ima single row or.column based on the given Condition. Itapplies some aggregate functions like! MIN, AVG, SUM and COUNT on groups, ORDER BY Clause ORDER BY clause is used to retr Particular order ic, either ascending. HAVING Clause HAVING clause is simil Used to pose the conditi clause, conditions are s. clause, conditions are Syntax @ eve the data it or descending lar to the WHERE clause, ions on groups. With ton rows and with HAN set on groups. © SELECT select ist : FROM from list GROUP BY grouping tist ORDER BY ordering list HAVING condition; Example ca SELECT Ename, DNo, MAX(Esal) FROM Employee GROUP BY Ename ORDER BY Esal DESC -Hfall the information is to be rettieved from a table then its syntax is as follows, SELECT * FROM table; SELECT * FROM Employee; ieee 1, INSERT Command ‘This command is used to add the information or column values to a fow in a table. Its syntax is as follows, INSERT INTO ‘table_name(column|, column2, column3, ..) VALUES(value!, value?, valued, INSERT INTO table_name VALUES(value|,value2, valve.) sample INSERT INTO Employee(Eid, Ename, Esal, ‘Age, Phone) VALUES("E-102", ‘David’, 28000, 35, 44004400); INSERT INTO Employee VALUES(‘E-02', ‘David’, 28000, 35, 44004400); ‘ From the above example, itis observed that at any time only a single row is inserted into the table. This is done based on the values specified for the columns. For instance, ifthe phone number of an employee is not known and a row is to be added in. the table then the inseftion can be done in the following two ways, {) _ INSERT INTO Employce(Eid, Ename, Esal, Age) VALUES(‘E-104", ‘Bechkam’, 30000, 32, NULL), (i) INSERT INTO Employee VALUES(‘E-104', ‘Bechkam’, 30000, 32, NULL); ; While inserting a new row, the following points must be considered, (a) When columns are defined with NOT NULL and DEFAULT option, then they shouldn't contain null values i.¢., default values must be assigned to them. (b), When columns are defined with NOT NULL option and values are not specified to them then the INSERT command fails to perform its operation thereby keeping the database unchange. (©) When a column is not specified with NOT NULL option then a mull value is assigned to it. 3, UPDATE Command This command is used to change or modify the existing column values of a row in a table. ts syntax is as follows, UPDATE table_name SET column_name = scalar expression WHERE condition; ‘The rows that satisfy the condition of the WHERE clause are updated based or the assignments given in the SET clause. Allthe rows in the table get updated whenever WHERE clause is not specified. Example UPDATE Employee SET Ei WHERE Age=30; ' Inthe above example, the Eid of an Employee whose age is 30 is set to “E-120" 4 DELETE Command ‘This command is used to delete the existing column values of a row from the table. Its syntax is as follows, DELETE FROM table_name WHERE condition; All rows, which satisfy the condition 6f WHERE clause are deleted. xample DELETE FROM Employee WHERE Bid = “E-210"; Inthe above example, all the students Whose Eid is “E-210" are deleted from the Employee table, ‘Whenever WHERE clause is not'specified, all the rows in a table gets deleted. Its syntax is, ee DELETE FROM table_name; DELETE FROM Employee; In the above example, all rows from the Employee table gets deleted. © SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS. 120° Data Definition Language (DDL) operant’ Pat Detnton Language (DDL) reas ers and dees relations na dts, The PPL- nero ie 1. CREATE 2. ALTER ; 3. DROP. 1. CREATE ‘The tables (or relations) in SQL are created using the CREATE TABLE command. Syntax CREATE TABLE table_name fe (Columnl_nanie datatype [NULL | NOT NULL [WITH DEFAULT] | UNION], (column2_name datatype [NULL | NOT NULL [WITH DEFAULT] | UNION], (columnN_name datatype [NULL | NOT NULL (WITH DEFAULT] | UNION), [Primary_key definition), [Alternate _key definitions}, [Foreign_key: definitions)); In the definition of CREATE TABLE command, column_name is the name of the column, data type is the type that the column will hold. The keywords NULL and NOT NULL are optional. These keywords specify the condi must be checked while inserting data into the table. Ifa column is specified as NULL then a NULL value will be inserted in that column if the user does not insert v accept that record and returns an error message. With NOT NULL, two other keywords WITH DEFAULT ot UNIO} also be specified. Both the keywords are optional. Ifa column is NOT NULL WITH DEFAULT, then the system} default value for that column if the user does not specify the value. For example, the default value for numeric data is 0 and for character data type is a space. If column is specified as NOT NULL UNIQUE then the system does ow the duplicate values for that column. Th¢ last three lines in the CREATE TABLE definition specify the prt alternate key and the foreign key for the new table Example ‘The following statement creates a new table named customer, CREATE Table Customer (cid INTEGER NOT NULL, cname CHAR(20), aceno’ INTEGER; fname _ CHAR(30) NULL, amt _ REAL NOT NULL WITH DEFAULT, Primary key(cid)); 2 ALTER 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) [ALTER [COLUMN] DROP DEFAULT) WARNING: xeronProlocopyng of i book is CRIMINAL Anyone found Guilty LIABLE o face LEGAL ‘ Deletion of column (©) Addition of constraint (d) Deletion of constraint (©) Setting a default value for a cohimn (0) Unsetting a default value fora column * ALTER TABLE Employee ADD Project_ Number INTEGER; % ALTER TABLE Employee; ALTER SEX SET DEFAULT 3. DROP Destroying or deleting 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 deletes the department table if ‘Some view or integrity constraint is referring to it otherwise, this command fail # DROP TABLE Department CASCADE; In this case all views and integrity constraint referring to the relation ‘department’ are deleted along with the table Data Manipulation Language (DML) I, Q24, 26. Define query processing and briefly exp! the steps involved in it. OR Discuss the functionality of query evaluation engine. (efer Only Topic: Query Evaluation) Answer : Query Processing ‘Query processing is a sequential process of retrieving ala from a database based on the input by performing **veral operations. The’ cost of processing a query is directly Proportional to the number of disk accesses. There are many ‘talegies (good strategy, bad strategy) that can be used for ing a complex query. The selection of the best strategy ‘Tucial point and therefore requires significant amount of "ime tobe spent, even ifthe query is being executed only once For answer refer Uni May A5(R13), 2(0) ®% SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS Steps for Processing a Query Following are the steps considered while processing a query. 1, Query parsing and translation 2. Query optimization 3. Query evaluation 1. Query Parsing and Translation The initial step performed during query processing is translation. In this, the user-entered query is translated into an internal form that is easily understood by the system. The Purpose of performing translation is that, the query entered by the user is in a format which is not understood by the system. ‘There are many internal forms of representing a query but among these, the most widely used internal representation is dependent on extended relational algebra A software called ‘Parser’ is responsible for performing. the translation process, This software will carry out the following activities, (Verifies whether the query entered is syntactically correct (ii) Verifies if the relation name specified in the query matches with the name stored in database. Gil) Construct a parse-tree (query-tree) for representing the query or expression using views (iv) Converts the parse-tree into relational algebra expression and if views are used then replace these views with relational algebra expression defining the view. 2 Query Optimization Query optimization is an essential activity of relational DBMS. In this step, the selection of an efficient query evaluation Plan is made. Itis the plan consisting of series of primitive operations using which a query can be evaluated. The selection 's done based on the estimate of cost associated with every evaluation plan, Itis the responsibility of the system to develop 4 query evaluation plan that reduces the cost incurred while evaluating the query. Practically, itis not possible to estimate the cost of every individual evaluation plan. Thus, in order to make 4 good cost estimate, optimizes can use statistical information such as size of the relation, the index depth, The relational query languages that a user uses for creating a query can either be declarative or algebraic. Declarative languages are the languages that allow the user to specify what ‘outcomes should be generated from the query. However, it does not specify the way, the system performs its operation for generating the desired outcome. Algebraic languages are the languages that perform algebraic transformation.-Once the User has specified the desired query language, the optimizer then easily generate multiple query evaluation plan. And from these plans, the plan with minimum cost can be selected, 3. Query Evaluation During query evaluation step, in addition to specifying. relational algebra expression, it is necessary to annote these ‘expressions using the instructions that determine the way of evaluating each operation. Such an expression is referred as “evaluation primitive”, ‘abn SYSTEMS LUNTU-HYDERABAgy MANAGEMENT for a specific operation. The y, sae ciao isesponsbl for evaluating yy ect 96 DATABASE ‘The purpose of such annotation is that it specifies the algorithm oF ox oy a ced by tn cptotlinge ea Eo te ‘Query using the plan. Once the query is evaluated, the result fart ‘Parsing and transintion Opemizer Query ‘ptziation Figure: Steps for Query Processing 927. Explain with example the significance of DISTINCT keyword. Answer : ‘Consider the following three relations, Employee Eid _| Ename | DNo | Esal Age Phone Ot] fone 128000) 56 loa sragtg 100} BAPY orl .3rf.8000- | 28 | 33079199 MOP aooer de nly 20000 | 35). | exeosing oT David . 30000 4 23535135 108. Samy csv ASOT | gatsear Boe pia Nveatoy Nae | nasresee 120 Smith 4 20000, 20 56408489 122 David 6 18000 2s 24517635 Department |g sal and Schema Refinement al 9 Months 14 Months 16 Months 25 Months 9. Months Select the names and salaries of the employees, whose salary is greater than 20000. ~ SELECT DISTINCT E.Ename, E.Esal FROM Employee E WHERE E.Esal> 20000, The result of this SQL statements is as follows Esal John | 35000 | Henry | 22000 | David} 30000 Sam__| 25000 Table: Result using DISTINCT Keyword The above table does not contain all the tuples whose salary is greater than 20,000. The tuple with Ename “Henry” is repeated ‘wie but is displayed only once. This is due to the use of DISTINCT keyword. If this keyword is not used then table is resulted. ‘The omission of DISTINCT keyword resulted in arrow (Henry, 22000) which is repeated twice. This is called as multiset of tows. Itcan be defined as a set consisting of unordered elements which may consist of many copies of same element but the total tunber of copies ofthe element is important. For example the set(1,2,1,1,) and (2,1,1,1) are same multiset, Both contains three copies of 1" and only one-copy of ‘2'. But the multiset(1,2,2,1) is different. Number of copies of each element is an important Stiteria to differentiate between two multisets. 28. Consider the following relations, Student(snum: integer, sname: string, major: string, level: string, age: integer) Class(name: string, meets at: time, room: string, fid: integer) Erolled(snum: integer, Ename: string) Faculty(fid: integer, fname: string, deptid: integer) Write the following queries in SQL, ()) Find the names of all juniors (level = JR) who are enrolled in a class taught by LLteach. {ii) Find the age of the oldest student who is either a history major or enrolled in a course taught by I teach. {(il)_ Find the names of all classes that either meet in a room R128 or have five or more students enrolled. (Wv) Find the number of all students who are enrolled in two classes that meet at the same time. J Aprii-tt, Sets, ® SELECT stsname ; es FROM Student 1, Class Cl, Enrolled Er, Faculty F WHERE St.snum = Ersnum AND Er.ename = Clname AND Clifid = Ffid AND F fname = ‘Lteach’ AND St level = IR’; ") SeLect max (St.age) FROM Student St (Stamajor = ‘HISTORY’ OR St.snum IN(SELECT Er Snum Class Cl, Enrolled ER, Faculty F WHERE Erename = CLname AND CLfid = Ffid AND F fname = “I-Teach’); ‘SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS | | a ee 98 DATABASE (iti) SELECT Cl.name FROM Class Cl WHERE Cl.room = ‘128° ‘OR Clname IN(SELECT Er, Cname FROM Enrolled Er GROUP BY Er. Cname (iv) SELECT DISTINT St.sname FROM Student St WHERE St.snum IN(SELECT Er, snum FROM Enrolled ooh Enrolled Er2, Cass Cll, Class C2 WHERE Erl sum = Er2.snum AND Erl.enam AND Erl.ename = Cll.name AND Er2.ename = CI2.name AND Cll.time = CI2.time); Q29. Write queries for the following using the given information, _Em DOB DOJ _[EmpSalary Buelin 06-12-1983 [07-08-2005 | 15000 07-08-2085 HAVING COUNT (*) >= 5); 1 <> Er2, ‘Andy 12-01-1970 |06-12-1973 | 20000 06-12-2043 Lubber 07-08-1985 |12-04-2006 | 13000 12-04-2056 Zobra 08-02-1960 |07-03-1982 | _25000 07-03-2032 {a) Find total salary of employees from emp table. (b) Find months between employee DOJ and.DOR from emp_schema. (c) Create new salary table using the empname and empsalary from existing table. (4) Arrange empnames in ascending and descending order. Answer : (2) __ Select sum(EmpSalary) from Emp_schema; (b) Select {(Month(DOR) ~ Month(DOJ)) + {(Year(DOR)~Year(DOS))]* 12] from Emp_ schema; (©) Create table salary as (select EmpName, EmpSalary FROM Emp_schema); (4) © Select * from Emp_schema ORDER BY EmpName ASC Select * from Emp_schema ORDER BY EmpName DESC; 3.1.2 UNION, INTERSECT and EXCEPT 30. Discuss about set operators with suitable examples. Answer : Set Operators Set operators merge the result set of two different queries into a single result set. necessary to ensure that every select statement must have same number of columns atid family. Following are the three commonly used ‘set operators in SQL: (UNION (i), INTERSECT Before using the St opéfatrs, every column belongs to same data (iii), EXCEPT. @ UNION UNION operator combines two or more result sets into single result set. Though UNION operator in functionality as join operation in relational alba, the former generates single eu set by merging mull the latter extends the row horizontally. There are two forms of UNION operator, Te (a) UNION DISTINCT] (b) UNION ALL. WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is ABLE to face LEGAL ‘operator retums: duplicate rows, Syntax SELECT columnl, cohumn?, UNION [DISTINCT] SELECT cotumn!, column, cotimn Example result set that doesn't contain any column... FROM Table] FROM Table2 SELECT E.ename, D.DNo, D:PNo FROM Employee E, Department D WHERE E.eid = D. Dept managerid AND D.PNo=44 AND D.Diocation = “Hyderabad? UNION DISTINCT SELECT El.ename, D1.DNo, DI.PNo FROM Employee E1, Department D1, WHERE E1.cid = D1. Dept_managerid AND D1.PNo = 44 AND D1 Diocation. “Bombay’; The above statement lists the unique names of the employees Who are working on project number 44 and project location is ether Hyderabad or Bombay. (b) UNION ALL This UNION operator returns the result set that contains duplicate rows. Syntax SELECT Column 1, Column2, Column3..... FROM Tablet UNION ALL SELECT Column1, Column2, Column3.. FROM Table2 Example SELECT E.ename, D.DNo, D-Diocation FROM Employee E, Department D WHERE E.cid = D.Dept_managerid AND D.PNo = 44 AND D.Dlocation ‘Hyderabad’ UNION ALL SELECT E1.ename, D1.DNo, D1.PNo FROM Eriployee £1, Department D1 WHERE El cid = D1.Dept_managerid AND D1.PNo = 44 AND D.Diocation = ‘Bombay’; The above statement lists all the names of employee (including duplicate names) who are working on project number 44 and project location is either Hyderabad or Bombay, UNION operators are generally used in many data atehouse applications because the relations in these i {are not perfectly normalized. This operator doesn't the order of rows (ie., rows of second relation may. ‘PPear before the rows of first relation), However, if specific User is 10 be followed then ORDER BY clause can be used With UNION operator. INTERSECT operator combines the result sets of two different queries into a single result set that contains only the columns which are common in both relations. INTERSECT ‘operator in SQL is similarto the inner join operator in relational algebra, but the difference is that the former finds the common columns vertically whereas the later finds it horizontally. The following are the two forms of INTERSECT operator, (a) INTERSECT {DISTINCT] (b) INTERSECT ALL, (a) INTERSECT {DISTINCT} This operator removes duplicate rows from the final result set. ” Syntax ELECT column], column2, column3,.... FROM Table INTERSECT [DISTINCT] SELECT column|, column2, column3..... FROM Table2 Example SELECT E.ename FROM Employee E WHERE E.DNo= 4 INTERSECT SELECT El ename FROM Employee El WHERE E1.DNo = 6; ‘Theabove statement lists the unique names of employees who are working for department 4 and 6, (b) INTERSECT ALY This operator doesn’t remove duplicate rows from the final result set. Syntax SELECT column, column?, column3.... FROM Table 1 INTERSECT ALL Example SELECT E.ename FROM Employee E WHERE E.DNo=4 INTERSECT ALL SELECT El.ename FROM Employee E1 WHERE E1.DNo=6; The above statement lists all the names of employees (including duplicate names) who are working for department 4 and 6, (i) EXCEPT EXCEPT operator combines the multiple result set of two different queries into single result set that contain the “Unmatched rows present in the result set of first relation, but ‘ot in the result set of second relation. This operator is similar {0 “Outer join” operation butte difference is that the EXCEPT, Finds the unmatched rows vertically whereas the outer join finds the unmatched rows horizontally. The two forms of EXCEPT operator are, (@)_ EXcEPrT [DISTINCT] (&) EXCEPT ALL, EXCEPT [DISTINCT] This operator retums a result set that doesn’t contain any duplicates. Syntax (a) SELECT column1, column2, column3.... FROM Tablel EXCEPT [DISTINCT] SELECT column}, cohumn2, column3.... FROM Table? Example SELECT D.Dname FROM Department D WHERE D.PNo = 44 INTERSECT SFLFCT DILDname FROM Department DI WHERE DIPNo = 55: The above statement lists the unique names of department that are controlling the project number 44 not project ‘number 55. EXCEPT ALL This operator returns a result set that contains duplicate rows. () Syntax SELECT columnl , column2, column3,..... FROM Table] EXCEPT ALL - SELECT column!, column2, column3..... FROM Table2 Example SELECT D,Dname FROM Department D WHERE D.PNo= 44 EXCEPT ALL SELECT D1Dname FROM Department D1 WHERE D1.PNo=55; The above statement lists all the departments (including duplicate departments) that are controlling the project number 44 not project number 55. set comparison operators supported by SQL, () IN (ii) ALL (iv) EXISTS. IN This comparison operator returns a value true clement is in the given set, otherwise, returns a value fl @ Example SELECT E.ename FROM Employee E WHERE E.eid IN (SELECT D.Dept_managerid FROM Department DWHERE D.DNo=6); ‘The above statement returns a value true for the Contains the names of employees who are working in umber 6, ‘The negated version of IN operator is NOT IN. operator checks if an element is not present in the given Example SELECT E.ename FROM Employee £ WHERE E.eid NOT IN (SELECT D.Dept 1 FROM Department D WHERE D.DNo~6); The above statement returns a value true for that contain the names of employees who are nat department number 6, ai) Comparison Operator> ANY a ris operator returns the value trie if there is record that satisfies the given condition, otherwise, Example : SELECT Eename FROM Employee WHERE E-Fsal> any, FROM. Employee Ei (SELECT ELesal UNITS" SQL and SthemaRéfinement’ ggg (if) ALL This operator retums the value false, ‘one record that doesn’t satisfy the condi true is retumed, if their is atleast n. Otherwise, a vélue Example SELECT B.ename FROM Employee WHERE E.esal > ALL (SELECT E2.esal FROM Employee WHERE E2.ename = Inthis example, E2.esalis calculated forthe subquery and all the tuples retrieved are compared with E.esal. If the sal: ofall the employees named ‘Henry*is greater than E-esal, thea a value true is returned, otherwise Value false is returned. (iv) EXISTS, “Henry’); EXISTS operator is a tes tuples satisfying the condition a value true only if the eval if the subquery returns at that satisf returned. Example SELECT E.ename FROM Employee E WHERE EXISTS (SELECT * st for checking whether the set of s is Not null. The operator returns luating subquery is non-empty (i.e, least one row that isnot null and ies the given condition). Otherwise, a value false is FROM Department D. WHERE D.DNo=6 AND D.Dept_managerid = F cid); The above statement returns a value true for the set of. tuples which satisfies the condition D.DNo = 6 AND, D.Dept_ ‘managerid = E.cid is not empty The negated version of EXISTS operator is “NOT EXISTS” that checks whether the set of tuples which satisfies the condition is empty, Example Inthe above example, “NOT EXISTS” operator retrieves Setof tuple for which a Value tnic is returned ie., the names who are not working in department number 6, 932. Explain the following operators in SQL with examples, (i) SOME (i) IN (ti) Except (iv) Exists. of May-17(815), 4(0) SR aapetiete svscricns mntcne joanne ron enamteemns stopers ——————— Explain the following operators in SQL with ‘exampl () SOME (i) IN (ili) EXCEPT iv) UNION. Answer : () SOME ‘SOME? operator is generally used in WHERE clause for verifying whether the value ofa specific column match with set of values returned by a subuery or not. Syntax SELECT column! FROM table! WHERE column! = SOME (SELECT column! FROM column1= ‘somevalue’); Example SELECT * . FROM Employee E WHERE E.salary = SOME Employee E WHERE E.salary April-18(R16), Q5(b) (SELECT salary FROM > 15000); The above statement returns a value for the column. containing employee’s salary greater than 15000, (ii) IN For answer refer Unit-II1, Q31, Topic: IN, (ili) EXCEPT For ancwer refer Unit-Ll, Q30, Topic: EXCEPT, ~ (iy) EXISTS For answer refer Unit-ll, Q31, Topic: EXISTS, (%) UNION -3 Nested Quer ies, Aggregation Operators 33. Whatis anested query?, Answer t Nested Queries Explain with an example. Model Paper-ii, 6(b) Example Find the names of employees who are orking i department number 6 7 ie Solution SELECT E.Ename FROM, Employee E WHERB E.Eid IN (SELECT D.Dept Managerid FROM Department D." A WHERE D.DNo=6);» ” 4 following manner, (1) The inner query is executed first, SELECT —_D.Dept_Managetid FROM Department D ‘Subquery WHERE D.DNo=6 This query retrieves the Dept_Managerid of all the employees whase DNo = 6 Next, the DBMS checks the presence of resultant value ‘of Dept_Managerid in employee table. If it exist then it displays the result for that id (i.e, the Ename). ‘The main query that contains the sub queries in called as outer query. The IN keyword can also be replaced with NOT IN keyword. In this case, it checks for the tuples which are not present in the given relation, Example; Find the employee who are not working in dept number 6, SELECT E.Ename FROM — Employee E WHERE — E.Fid NOTIN (SELECT D.Dept_Managerid FROM. Department D WHERE D.DNo= 6); @34. With an example, explain the optimization of nested sub-queries. Answer : Optir aw jon of Nested Sub-queries Nested sub-queries are placed under the “WHERE” clause in the form of parameterized function, which returns a single value or set of values. Basically, the parameters passed ‘within the functions are the variables (correlation variable) derived from the outer level query. The evaluation of nested ‘query is done by initially computing the cross product in the outer “FROM” clause. After computing the product, the predicates in the “WHERE” clause are tested for every ‘individual tuple in the resultant product. Such way ofevaluating a query consisting of nested sub-query i referred to as correlated ‘evaluation, The drawback of this evaluation technique is that itis inefficient as more disk inpuVoutput are required. This is because, every sub-query is evaluated separately by considering every tuple in the’outer level query Therefore, to overcome this issue, SQL uses an optimizer that convert nested sub-queris into joins wherever itis possible to perform such conversion. In situation where conversion isnot these SQL optimizer maintains each of the sub-query [separate expression and then optimizes each query separately. Once every sub-query is optimized, correlation evaluation is performed so as to evaluate the sub-queries possible, Example ‘Consider the following query (Q,) - SELECT sid FROM Sailor, Reserves ‘The execution of this nested subquery is done in ‘anested sub-query canny then in such situation, a tempora the information about the: rng anested query without section. i ‘correlation variable from the outer eatin crete EY combined with outer level ohne Si Consider the following instance of que SELECT.» FROM. 1, WHERE, AND! In the above query, predicates and can be rewritten 3, CREATE TABLE Tab! AS SELECT DISTINCT Att FROM, WHERE C}, SELECT... FROM C,, Tab WHERE C, AND C3 Here, C} consists ofpredicate in C, without the sees consisting of correlation variable and C3 redefines sel with correlation variable, “Att” specifies all aftribute used selection consisting of correlation variable Query(Q,) can be transformed to, CREATE TABLE Tabl AS SELECT DISTINCT sid FROM Reserves.” SELECT sid FROM Sailor, Tab! EXISTS(Select | * FROMT, WHEREC; €, is a conjunction of simp WHERE Tabl.sid = Sailorsid; Write the following queries in SQL using) queries concept for the following schema, integer, sname: string, rating: al) . Boats(bid: integer, bname: string, colo Reserves(sid: integer, bid: integer, di (i) Find the names of sailors who have served both red and green boat. (ii) Find the names of sailors who have served all boats. f (ii) Find the names of sailors who h reserved red boat. (iv) Find sailors whose rating Is some sailor called Raghu. Q35. WHERE Sailorsid = Reserves.sid; WARNING: Xerox/Photocopying ofthis book is a oRIMINAL Anyone found guilty LIABLE to face LEGAL Pros ‘ APENAT, Set, CTY) ‘S.sname S.sid = Rsid AND, Robid = B.bid AND Beolor = ‘Red’ AND S.sid IN(SELECT 82.sid FROM Saitors $2, Boats B2, Reserves R2 WHERE $2. sid = R2.sid AND R2.bid = B2,bid AND B2.color = ‘green’); ‘SELECT S.sname FROM. StilorsS NOTEXISTS(SELECT B. bid FROM Boats jp WHERE NOT EXISTS (SELECT R.bid FROM eserves R WHERE R. bid = B.bid AND R.sid=S.sid)); @ SELECT S.sname FROM Sailors S WHERE S.sid NOT IN (SELECT R.sid FROM ‘Reserves R WHERE R.bid IN (SELECT B.bid FROM Boats B WHERE B.color = ‘red’); y) SELECT S.sid FROM Sailors S g > ANY (SELECT S2.rating ‘Gi6. What is correlated nested query? Explain with an example. daswer Correlated Nested Query Ifthere is a relationship between outer query and sub ‘ger then such queries are said to be correlated nested queries. Euample Find the names of employees who are working in ‘partment number 6. ‘SELECT E.ename FROM Employee F WHERE EXISTS (SELECT * FROM DEPARTMENT D WHERE D.DNo=6 AND D.Dept_Managerid = E.cid); EXISTS is a set comparison operator which checks “eter tte et is not null (non empty). In this example, for ‘Employee name, ‘EXIST’ operator checks whether the Hiplitples which satisfies the condition D,DNo = 6 AND om = Eeeid is not empty. If the resulting set Aprilt1, Set, Q7(b) trae that means some Employee E is working in ag ett mumber6, Here, the sub query is dependent onthe gle ne. That is each tuple of department is dependent on wer, The specified condition is checked for each te. , Thus, the statement, Sailors S, Reserves R, Boats B t D.Dept_Managerid = hence termed as correlated query. IENOT EXISTS is used, then the names of Employees who are not working in department number 6 are Inaddition to EXISTS, NOT EXISTS keywords the user can even use another set-comparison operator called UNIQUE. This operator is used to eliminate the duplicate rows (1.6. the rows that appear more than once) when UNIQUE is used with sub query then itensures that all the retrieved rows are unique. Similarly NOT UNIQUE operator returns true if there are duplicates in the table. 37, What aggregate operators does SQL support? Explain with examples. Answer : Aggregate Operators ‘Aggregate Operators (functions) improves the data retrieval property of SQL statement. These operators enables the users to summarize the data retrieved from the relations. Basically, the aggregate operators takes the entire column of data as its argument and generates a result set that summarizes the column. The following are the different aggregate operators supported by SQL, ‘April-10(R16), OAD) 1. COUNT 2. SUM 3. AVG 4. MAX 5. MIN. 1. COUNT COUNT followed by a column name returns the number of tuples in the specified column. If DISTINCT keyword is used then it will return only the count value of unique tuples otherwise it will return count value of all tuples (including duplicates). Syntax SELECT COUNT ({DISTINCT] column-name) FROM WHERE condition; Example Count the number of different employee names, SELECT COUNT (DISTINCT E.empname) FROM Employee E; 2... SUM. SUM followed by a column name returns the sum of all the values inthe specified column. If DISTINCT keyword is used then it will return the sum of all unique values in’ the columns otherwise, it will return the sum ofall values (including duplicates) in the columns. ke Syntax SELECTSUM [DISTINCT] Column_name FROM table_name WHERE condition; table-name SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS es] — a Tid indicates the correlation and Example So ‘MAX (column-name) (column Find the sum of salari 5 SELECT salaries of all the employees, a SELECT SUM(E esal) wHene? eclod FROM _ Employee E; iat OMAVE Find the name and age of eldest-employee, AE AVG followed by a column name retums the average Sees re value of all the values in the specified column, If DISTINCT FROM Employee E Keyword is used then it will return the average of distinct values WHERE E.age = (SELECT MAX (E2.age) only. Employee E2); Syntax ; 5. MIN wa MIN followed by a column name returns the m SELECT AVG ( [DISTINCT] column-name) value from the values present in the specified column, FROM table-name Syntax WHERE condition; SELECT MIN (column_name) Example FROM table_name Find the average age of all employees, HEE Comtitions Example SELECT AVG (E.age) Find thg name and age of youngest employee, FROM Employee E; SELECTE.empname, E.age 4 MAX FROM Employee E MAX followed by a column name retumns the maximum WHERE Eage (SELECT MIN(E1 age) value from the values present in the specified column, FROM Employee, Q38. Compare nested query and correlated query. Discuss suitable examples. Answer : Nested Query Correlated Query In nested query inner queries are not dependent on | 1 In correlated query inner queries are dependent on Ot outer once. once, * Inner query is executed first. Outer query is evaluated first It consume less time. It consume more time, {tis simple. Itis relatively complex. Inner query is executed only once. Inner query is executed for every tuple present in. outer query. It does not effect the system performance. It is easy to understand. 1. Iteffects the performance of the system. highly. Itis relatively difficult to understand. Example Example For answer refer Unit-IIl, Q33, Topic: Example For } wer refer Unit-IIl, Q36, Topic: Example, Q39. What is the usage of ‘group by’ and ‘having’ clauses in SQL? Answer: GROUP BY Clause $ GROUP BY clause is «clause used for grouping the data of abe in a single row column based on some grouping This clause is defined within the SELECT statement and is used in conjunction with aggregate functions. However functions are riot used then execution of GROUP BY clause generates “not a GROUP BY expression” error can be said that a GROUP BY clause is valid only if used in combination with aggregate functions. GROUP BY easily creating frequency distributions within the SELECT statement. WARNING: xeroxPhotocopying of this book i @ CRIMINAL act. Anyone found guilty is LABLE to face LEGAL Syntax SBLECT coll, e012, ..... FROM Table_name(s) (WHERE condition! condition?, (GROUP BY coll, coi...) TORDER BY coll, col2 lASC/DEscy; Example SELECT. Emp_name, MAX(Emp_ salary) FROM Employee GROUP BY Emp name ORDER BY Emp salary DESC: twedto eliminate rows. The ‘Having’ clause is always used is ‘conjunction with the “GROUP BY” clause. Syntax SELECT coll, col2, FROM — Table_name(s) (WHERE condition!, condition2, .....] [GROUP BY coll, col2,.........] {HAVING condition!, condition2, ........] (ORDER BY coll, col2, ....ASC/DESC]]}; Example SELECT Emp_name, MAX(Emp_salary) FROM — Employee GROUP BY Emp_name HAVING MAX (Emp_salary) > 10000 ORDER BY Emp salary DESC; The above query determines the maximum salary among HGS etaployees and group them using Emp_name only ifthe Salary of respective employee is greater than 10000, Finally, esult is listed by Emp_salary in descending order. Se o> SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS ay: i ae Q40. Consider the following schema, Sallors(sid, sname, rating, age) Boat(bid, bname, bcolor) Reserves(bid, sid, day) Write the following queries in SQL, (i) Find the average age of sailors with a rating of 10. (ii) Find the name and age of the oldest sailor. (ili) Count the number of sailors. (v)_ Count the number of different sailor names (¥) Find the names of sailors who are older than the oldest sailor with a rating of 10. (vi) Find the age of the youngest sailor for each rating lev (vil) Find the age of the youngest sailor who. is eligible to vote (i.e., is at least 18 years old) for each rating level with at least two such sailors. (vill) For each red boat, find the number of res- ervations for this boat. (0) Find the average age of sailors for each rating level that has at least two sailors. (x) Find the average age of sailors who are of voting age(i.e., at least 18 years old) for each rating level that has at least two sailors. (xi) Find the average age of sailors who are of voting age(i.e., at least 18 years old) for each rating level that has at least two such sailors. ') Find those ratings for which the average age of sailors is the minimum over all rat- ings. Answer : @ SELECT AVG (S.age) FROM Sailors $ WHERE S.rating = 10; (i) SELECT — S.sname, MAX (S.age) FROM Sailors S; (iii) SELECT COUNT (*) FROM Sailors ; (vy SELECT COUNT (DISTINCT S.sname) FROM Sailors $; w SELECT §.sname FROM Sailors $ * WHERE S.age> (SELECT MAX (S2.age) FROM , Sailors $2 WHERE S2 rating = 10); (vt) Ifwe know that ratings are integers in the range 1 10 10, ‘we could write 10 queries of the form: SELECT MIN. (S.age) FROM Sailors § WHERE — S,rating =i; or SELECT [DISTINCT] select list FROM fromh-ist WHERE — qualification GROUP BY grouping-tist HAVING grouip-qualification; SELECT — S.rating, MIN (S.age) As minage FROM Sailors $ WHERE S.age>= 18 GROUP BY S rating HAVING COUNT (*)> 1; SELECT B.bid, COUNT (*) AS sailorcount FROM Boats B, Reserves R. WHERE Rbic bid AND B.color= ‘red’ GROUP BY B.bid; SELECT S.rating, AVG (S.age) AS average FROM Sailors S GROUP BY S,rating HAVING COUNT (*)> 1; @® SELECT S.rating, AVG (S.age) AS average FROM Sailors S WHERE S.age>= 18 GROUP BY S.rating HAVING1<(SELECT COUNT (*) FROM Sailors $2 WHERE S.rating = $2,rating); SELECT S.raling, AVG (S.age) AS average FROM Sailors § WHERE = S.age > 18 GROUP BY S. rating HAVING 1<(SELECT COUNT (*) FROM Sailors $2 WHERE $ rating = $2.rating AND S2.age > 18); SELECT S.rating FROM Sailors § WHERE AVG (S.age) = (ii) (viii (x) (i) Gil) ‘SELECT MIN (AVG (82.age)) FROM Sailors $2 GROUP BY 82 rating); WARNING: xeroxPhtocopying ofthis book is 8 CRIMINAL ac ‘Anyone found quill is LIABLE lo face LEGAL ps arg the following relations, sname: Oat. Ce Student(snum: integer string, fd: intoger) Enrolled(snum: integer, cname integer) Write the following queries in SQL, (i) Find the names of students not any class. (ii) Find the names of students enro maximum number of classes. Print the level and the average students for that level, for each Print the level and the average students for that level, for all levels e» (iii) (iv) Answer : @ SELECT DISTINCT S.sname_ FROM Student § WHERE S.snum NOT IN (SELECT E.sn Enrolled E); (ii) | SELECT DISTINCT S.sname FROM Student $ WHERE S.snum IN (SELECT EL. FROM Enrolled E1 GROUP BY EL.snum HAVING COUNT (*)>= 1) ALL (SELECT COUNT (*) FROM Enrolled E2 GROUP BY E2.snum)); 99 SELECT S.level, AVG (S.age) FROM Student § (iii) GROUP BY S.level; SELECT S.level, AVG (S.age) FROM Student (iv) GROUP BY S.level;_ {UNIT SOL end Schema Refinement 3.1.4 NULL Values Answer t ‘Model Papert, Q6{b) ull Values Null values are those values which are assigned to an attribute i cable. These values if its value is unknown or is not applicable. sewed by DBMS when the user does not now the typeof information tobe entered fora particular field. When the user doesn't smterany value fora field then uppercase DBMS assigns a NULL value to that field. A NULL value does not represent a Zero OF sates it just means the absence of value for that field and this value can be inserted later ‘Example In the employee table itis not necessary that all the employees should have a phone number, so forthe employer who oes not have a phone number, a NULL value can be assigned. When a tuple (124, ‘Kelly’, 6, NULL, 26, NULL) is inserted in employes table then forthe attributes e sal and phone NULL values are assigned. Assignment of NULL value simply indicates that ‘the value isnot known or is inapplicable for that attribute. A field which is not declared as NOT NULL can have NULL values. NULL values are used to deal with the exceptional data or the data that is not complete. Any operation performed on null values say result into inconsistent data, due to which usage of null values are not prefefred in a relation. Comparison using NULL Values It is difficult to perform comparison of valid values with NULL values if two valued Logic - TRUE or FALSE is used. Therefore to avoid this issues three valued logic - TRUE, FALSE or UNKNOWN must be used with NULL value. For: example, ifa NULL value is entered for salary attribute of Kelly and if a condition that queries to list all the employees whose salary > £20000 is specified. Then the evaluation of this condition for Kelly is UNKNOWN because salary is a NULL value for Kelly. Similarly, for other comparison operators (>, <, =, =), the evaluation of the condition will always be unknown: ‘SQL provides IS NULL, is NOT NULL comparison operators to compare the NULL values i.e., to test whether a value is NULL or not. IfisNULL operator is applied to salary attribute then ‘TRUE’ value is returned which specifies that esal attribute isanill value, And if is NOT NULL operator is applied to same attribute, then FALSE value is returned. 043, Explain in detail about logical connectives AND, OR and NOT. Answer : Logical connectives with NULL values must be defined using three valued logic wherein expressions evaluates to three ‘aloes (Le,, to TRUE, FALSE or Unknown). For example consider the following query. Examples List all the employees whose age is less than 40 whose salary is greater than %30000. SELECT * FROM — Employee E WHERE — E.age<40 AND E-esal>30000; All the tuples that satisfy this condition are selected but what about the tuple consisting of esal as NULL value. In this ‘se, this condition will evaluate to unknown Logical operators which involves at least onc column whose value is assigned as NULL will always result in-aft unknown value. The following table will give a better understanding of logical ‘operators when, ‘ved with null values. Result and Reason TRUE If both X and Y are true FALSE Ifeither X or Y is false () XANDY UNKNOWN _ Ifeither X or Y is unknown (mull values) TRUE Ifeither of them (X or Y) is true FALSE Ifeither of them is false UNKNOWN [fone of the argument is false and other is unknown’ TRUE IfX is false FALSE TEX is true (ii) XORY eee ee ee soe ‘values on SQL constructs. tovunderstand the impact of NULL values on th, Q44. Explain briefly the impact of null Answer: + ‘As many boolean expression are used in SQL, it is necessary. constructs, Consider the foll Example List all the names of students who belongs to group * SELECT |* FROM Student S WHERE S.Group = ‘B’; This solution will result in the set of tuples that satisfies the ‘WHI this condition are ignored. In addition to these tuples, the tuples with NUL! tuples the condition evaluates to false or unknown. Thus elimination of rows that resulted to unknown, cn the queries, specially the nested queries consisting of) EXISTS or UNIQUE keywords. We know that the comparison of any two fields with null vslues for equality is an unknown value. But when ite (© equality operator, the two null value attributes are treated as equal. Ifa field contains two null values then that is consi duplicate values. Iwo tuples are said to be duplicates they hold dhe saine value or if they hold the nll values. So, the 6 ‘of NULL values with the “=" operator always results in TRUE. ‘The result of all the arithmetic operators (+, —,% /, *) results in an unknown value (NULL) if any one of the is a NULL value, Similarly with all the aggregate operators the result is NULL if these operators are applied to a NULL) ‘Aggregate functions simply delete the NULL values and then returns the result of aggregate operator i.e., SUM, AVG, MIN, COUNT(DISTINCT) simply delete/ignore the NULL values and returns the result of other NOT NULL tuples. Only in aggregate operator is count(*) which does not ignore/delete, The NULL values, it counts them and thert retum the m IERE’ condition and al other tuples that does nots ‘L values are also ignored (eliminated) because fort (have significant i tuples in the table. Q45. Write short notes on disallowing of null values. Answer ‘The insertion of NULL values for a field can be restricted by specifying the NOT NULL constraint within the field definities, This implies thatthe field cannot take null values. For the primary Key field itis mandatory to include It is constraint as these fields are not allowed to consider null values. Basically, the NOT NULL constraints specifies for every primary key field. Example CREATE TABLE Student (Sid INT NOT NULL, ‘Sname CHAR(10) NOT NULL, Project VARCHAR(I5), Class INT, PRIMARY KEY(id)); Sid is the primary key hence it must be unique and it should be NOT NULL. In the above example, the project taken up by the student. Tis field can take NULL values asi is possible thata student is not projectinot yet assigned a project. However, if this field is not allowed to take NULL. values, then the NOT’ be specified within the field. a ‘ WARNING: Xerox/Photocopying of this book is a CRIMINAL act. ‘Anyone found guilty is LIABLE to face LEGAL eel ‘SQL and Schema Refinement tee OO 315 Complex Integrity Constraints in SQL ‘ats, Discuss about complex integrity constraints in SQL triggers. May-13(R09), ab) oR Explain various Domain constraints in SL with ‘examples. [RefeF Only Topic: Defining Domain Constraint) Answer ¢ Complex Integrity Constraint in SOL Integrity Constraints can be applied on single columns, ‘nd also on group of tables (called assertions). This section jes the following features on different integrity constraints thatcan be applied on table or group of tables, 1, Constraints Applied on Single Table with Check Option ‘Constraints that are applied on a single table are called ‘uble constraints* and can be applied on the table with the help ‘ofcheck option. Constraint is a condition that must be satisfied byatable and check option is used to check that condition, For ‘ample, if we want to make sure that all the employee's salary sist be greater than 15000 but ess than 40000 is an employee relation, we can insert this condition at the time of creation of employee table. We may writ ) CREATE TABLE Employee(eid INTNUDNULL, May-49(R16), a4gv) ename CHAR(20) NOT NULL, DNo INTNOT NULL, esal DECIMAL(10,2), eage INT NOT NULL, Phone CHAR(18), PRIMARY KEY(cid), FOREIGN KEY (dNo) REFERENCES Department {DNo), CHECK (esal > = 15000 AND esal __When new tuple, are inserted into the table, the check Sendition is evaluated. If it returns true then the row is inserted the itis rejected, a 40000); Defining Domain Constraint New domains can be defined in SQL, by using the Aatement CREATE DOMAIN. In addition to this, we can even ‘atic the values of new domains by using check option. This eans that itis possible to specify the ranige of values that these *¥ domains can take. The syntax for creating a new domain is, CREATE DOMAIN Domain-name Source domain (Default value) CHECK (VALUE) * Create Domain: A statement or a Key word used to Mine anew domain, Domain Name: Name of the new domain ‘SPECTRUM ALL-IN-ONE JOURNAL 109° ‘Souree Domain Name? Name of the source domain * from which new domain is derived. % Default Vs fe can also provide default values for the domains : 4 Check: The option is used to restrict the values in the particular field (for which a new domain is soos This option provides condition that must be.cl by all the tuples of the column. : % Value: This keyword is used to provide a value to @ domain variable * For example, we can create a new domain for salary by stating these SQL statements “ CREATE DOMAINsalary DECIMAL DEFAULT 15000,00 (CHECK(VALUE>~ 1500.00 AND VALUE 4000.00) “Salary*is the new domain whose source domain is decimal. Now whenever the salary domain has to be referred it indicates that the values allowed for this domain is of decimal type. Default value for salary is® 1500.00 i.e, ifthe user did not enter the salary, then the default value will be & 15000.00 CHECK (VALUE >= 15000.00 AND VALUE 4000.00). This statement is used to check that all the inserted must have a value specified if this range. 3 eral Table: Assertions Assertions are group of tables on which a constraints are applied, Unlike table constraints which are applied on single table, assertions are applied on, multiple tables. Defining Constraints Over For example, consider that the total number of employees working as department manager and project manager must be exactly 20, then the following condition can be enforced, CREATE TABLE Dept_ manager (cid INTEGER, name CHAR(10), No INTEGER, esal DECIMAL(10,2) cage INTEGER, Phone CHAR(8), PRIMARY KEY (id), CHECK (esal>= 15000,00AND esal<= 4000.00) cr TECK (SELECT COUNT(Eeid) FROMemployeeE) + (SELECT COUNT (D.dept_managerid) FROM Department D) + (SELECT COUNT (PProject 1 FROM PROJECT P) <2) This SQL statements provi i Gitte dvs of tas Go ne eae employer table whereas hoth department aid project able must also be involved equally It is a complicated way of writing the statements to enforce the condition. More simpler way is tg create assertions of these three tables as shown below. FOR ENGINEERING STUDENTS aD a | 110 CREATE ASSERTION Total CHECK (SELECT COUNT (E eid) FROM employee E) + (SELECT COUNT (D.Dept_managerid) | FROM Department D); + (SELECT COUNT (PProject_mdnagerid) FROM Project P)<20)) With assertions we are required to only specify. the conditions that must be applied on group of tables. Q47. What are integrity constraints? Define the terms primary key constrains and foreign key constraints. How are these expressed in SQL? Answer : May-17(R15), 5) Integrity Constr: Integrity constraint is a mechanism in which certain rules are imposed on column or on table to. prevent users from entering invalid data. ‘The various types of integrity constraints available in PL/SQL are, ts PRIMARY KEY constraint FOREIGN KEY constraint NOT NULL constraint UNIQUE constraint 5. CHECK constraint. PRIMARY KEY Constraint It 1s used to define a column or group of columns that can distinctively identify every row in the table. 8 pe Syntax CREATETABLE table_name (coll datatype NULL/NOT NULL, col? datatype NULL/NOT NULL, col3 datatype NULL/NOT NULL, 1 CONSTRAINT const_name PRIMARY KEY (coll, col, .. eoln)); Here, coll, col2, col3 represents the column name that defines the primary key. Example CREATETABLE STUDENT ( std_id © INTEGER NUTNULL, sid_name VARCHAR2(50), sid_address VARCHAR2(50), CONSTRAINT student_pk PRIMARY KEY (std_id); | Calculus (DRC). In the above example, std_id is the primary key. Ifthe | (b) Specifying Foreign Key user inserts repeated values for “std_id” then error occurs a ‘and constraint name is returned indicating violation of For answer refer Unit-III, Q47, constraint. Constraint, JRiNliNAL BE IAHione found quit ts LIABLE to face WARNING: Xerox/Photocopying of this book is a Ct int It's used to determine any column that refer PRIMARY KEY in the other ee n between two columns rest in : distinot tables, Inorder t0 define a column = af “foul be primary hey inthe table co which Syntax CREATE TABLE table_name (coll datatype. NULL/NOT NULL, col2. datatype. NULL/NOT NULL; coin datatype NULL/NOT NULL, Foreign Key Constral CONSTRAINT fk_col FOREIGN KEY REFERENCES primarykey_table (coll, €0l2 yi é 4 Example Syntax for applying foreign key is as follows, (coll, col2, CREATE TABLE Department(Dname DNO INTEGER, Manager id INTEGER, PRIMARY KEY (DNo, Manager_id), FOREIGN KEY (Manager_id) REFERENC! (Employ The statement FOREIGN KEY (Manaj REFERENCES Employee - means that the “Manager id” uses primary id “Eid” of employee a reference. Every tuple with Manager_id must in employee relation. 48, Explain about the following, (a) Domain relational calculus (b) Specifying foreign key constr with an example. Answer ¢ (a) Domain Relational Calculus For answer refer Unit-II, Q27, Topic: Do yNIT-B SOL ahd Schema Refinement ae Gud. Consider the following relations Sailors (sid, sname, rating, ge) Boats (bid, bname, color) Reserves (sid, bid, day) Write the statements in Relati Caleu lational Torte following queatons, "= 0% Relatona Caleta, Doman Redon ate and SOL 18) Find the names of sailors who have reserved a Red boat. (b) Find the names of sailors who have reserved at least one boat. {c)_ Find the names of sailors who have reserved a Red and a Green boat. (d) Find the names of sailors who have reserved a Red or a White boat. (¢) Find the names of sailors who have reserved all boats. canes): Nov.(Dec.-18(R16), OS (4) Names of Sailors who have Reserved a Red Boat Relational Algebra Fe Gre = naz BOats) >< Reserves va Sailors) Relational Calculus For answer refer Unit-II, Q30(i), Domain Relational Calculus 4 {(N)/31,T, A(G,N, T, A) € Sailors 43 (1, Br, D) € Reserves a4 (Br, BN, Red’) € Boats)} 1. SELECT S.sname FROM Sailors $, Reserves R, Boats B WHERE S.sid=R.sid AND R.bid=B.bid AND B.color = ‘Red’; {b) Names of Sailors who have Reserved at least One Boat Relational Algebra Togsg (Sailors >< Reserves) Relational C: For answer refer Unit-II, Q30(ii). Domain Relational Calculus ((N)| 31, TA (UN, T, A) e Sailors » 3 (Ir, Br, D) € Reserves)} ‘ulus SOL SELECT S.sname FROM Sailors S, Reserves R. WHERE S$ sid = R.sid (6) Names of Sailors who have Reserved a Red and a Green Boat Relational Algebra PCTempred, 1. (sy ey Boats) >4 Reserves)) plTempreen, 7, (0... sou Boats) >* Reserves)) Tagua (Tempred >) Tempgreen) + Sailors)) Relational Calculus “{N{ Se Sailors A (S.sname = N.sname 3Re Reserves (S sid =R.sid » 3Be Boats (B. color =“Red” bid =R bid))) a 13Se Sailors (Ssname = Nsname 0 3Re Reserves (Ssil= Rid 3B Boas (8 color = “Green” a B id = R bid) Pomain Relational Calculus ' {QN)| 31, T, ALN, T, A) € Sailors 4 3 Bri, Br2, D1, D2 € Reserves ((Brl, BN, ‘Red’) < Boats ~ 3 (Br2, BN, ‘Green’) € Boats 4 Brl # Br2))} ae ‘ SPECTRUM ALLIN-ONE JOURNAL FOR ENGINEERING STUDENTS Boba gels 112 DATABASE MAI sou a SELECT S.sname FROM. Sailors S, Reserves R1, Boats BI, Reserves api WHERE S.id=Rl.sid AND R1.bid = BI.bid AND Ssid=R2.sid AND R2.bid = B2.bid AND Bheolon=*Red? AND B2.¢olor = ‘Green's (a) Names of Sailors who have Reserved a Red or a White Boat r Relational Algebra ; PCTempred, ry (Cu, nny Boats) ¥ Reserves)) pCTempwhite, n,, (0... «gaye Boats) > Reserves)) Team ((Tempred Tempwhité) > Sailors) Relational Calculus (N|38e Sailors » GRe Reserves (S.sid = Rsid A3Be Boats (B.bid =R.bid « (B.color Domain Relational Calculus {N)|31, GA G,N. TA) € Sailors 4 3(1, Br, D) € Reserves 4 (Br, BN, ‘Red’, ‘Green’ € Boats))} =“Red” v B.color="" sQu . SELECT S.sname FROM Sailor S, Boats B, Reserves R WHERE S.sid=Rsid AND Rbid=Bbid AND (B.color= ‘Red’ OR B.color = *White’); (©) Names of Sailors who have Reserved All Boats Relational Algebra p(Tempsid, (r,,,,, Reserves))n,, Boats) r,.,,,(Tempsids >4 Sailors) Relational Calculus For answer refer Unit-Il, Q30(iv). Domain Relational Calculus {@) | 31,7,A GN, T,A) Sailors » VB, BN 1 C (-(B, BN, C) € Boats) v (3 (lr, Br, D) € Reserves (=IR ABr=B)))} SQL SELECT S.sname FROM © Sailors S WHERE NOT EXISTS (SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid FROM Reserves R WHERE Rssid = S.sid)); 3.1.6 Triggers and Active Databases 50. What is a trigger and what are its 3 parts? Explain in detail. Aprittt, Set, OR What is trigger? Explain how to implement triggers in SQL. Answer: (Model Paper, Q7(a) | Aprit-18(R16), ‘Trigger ‘A trigger can be defined as a program that is executed by DBMS whenever updations are specified on the database’ More precisely, itis ike an event which occurs whenever a change is done tothe tables or columns of the tables. Only DI ‘specify triggers. ” ‘The general format of the trigger includes the following, (a) Event - *() Condition (©) Action. WARNING: Xerox/Photocopying ofthis Book s @ CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL ll 0 ‘ ging tt: yent describes the modifications 7 4 lows re Hone to the database which lead tothe activation of trigger. The fo es e (©) tering rein deleting columns ofthe tables or rows of tables may activate the trigger. , Creating, altering or dropping any database objec ‘ay also lead to activation of triggers. (© Anerror message or user logon or log.off may ‘also activate the trigger. és o ¢ Conditions are used to specify whether the particular act formed i r ‘he aluated to true ten the respective action is taken otherwise the action is selec, moan: @ 4 ‘Action describes the step to be taken when the correspondin aa i ; . evaluates to true. It is a calletion of SOL statements that are excewed as apart of ter nae en p kis possible to activate the trigger before the event or aftr the event : For example, consider the following trigger description wherein the trigger “emp-count” counts the number of employees (CREATE TRIGGER emp-count BEFORE. INSERT ON EMPLOYEE /* Event */ ; DECLARE Count INTEGER BEGIN 1 etion » Cou :=0 END This example clearly explains that the trigger must be activated before each insertion into the employee table and the action tobe taken whenever an insertion is made. This was an example showing. The activation of trigger before the event. Now, consider this example, which shows the trigger activation after the event CREATE TRIGGER count-emp AFTER INSERT ON EMPLOYEE /* Event */ WHEN (new salary < 20000) ee rAci iow Coniition */ BEGIN Count := Count +1; > 1 Action #/ END In this example, trigger count-emp is activated after the insertion of new record and if the condition evaluates to TRUE ‘hen the action is executed. There are two types of triggers. They are, (@) Rowsevl (©) Statement-level. 9) Row-Levet ‘Triggers 2 Row-lével triggers are the triggers that run for each row of the table that is affected by the event of triggers, ) Statement-Level Triggers “ Statement-level triggers ure the triggers that are executed only once for multiple rows which are affected trigger action, i ae is H is activated for multiple rows ofthe abl Inthe described previously, the emp-count sa statement-Jeve trigger as its activated fo Whereas coun-emp isa row-level rigger because itis activated foreach row of te table where salary is greater than 820000 114 DATABAS — Q51. Explain about assertions. r Answer: Assertions : can terion 88 follows, ‘An assertion refers to 4 constraint defined over a single/multiple tables. ‘The syntax of CREATE ASSERTION CHECK

You might also like