0% found this document useful (0 votes)
28 views16 pages

Unit 2 ST 2 Notes-1

Notes of database management system hn

Uploaded by

xech.0017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
28 views16 pages

Unit 2 ST 2 Notes-1

Notes of database management system hn

Uploaded by

xech.0017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
422. Data Manipulation Language (DML) DML is the part of SQL that manipulates the dat DML are SELECT, INSERT, UPDATE and DELETE, depending on query. a in the database. The statements you can use in DML statement can vary from simple to complex SELECT Statement The SELECT statement is most used statement in SQL. Every query must begin with SELECT statement. The following are example of SELECT statement. Syntax: SELECT *|ColumnNamet, ColumnName?, ~~ FROM TableName WHERE ColumnName = Expression ; Example: SELECT * FROM Book WHERE bkTitle = ‘Taxonomy of DBMS’ ; This statement return following result set (Assume one row is already inserted) bkNo biritle bkAuthor bkPublish 1234 Taxonomy of DBMS AGUPTA LAXMI PUB FROM Clause SEI “here oxi! statement always has FROM clat ata is suppose to access, in this examp! JM clause indicate the table or view name from use. The FRO! : n from data will be retrieve. Je Book is the table name ————_-—S—hehkekeketettt”~— 102 Database sing, WHERE Clause . ‘ in criteri in WHERE clause cong, ‘The WHERE clause filters rows that satisfied certain criteria given in W cay this example the criteria of row selection is BkAuthor = ‘A GUPTA’ This clause is used for: following pan © Toreview: The WHERE clause tells which records to consider in the query results, © For each record, the WHERE clause has to be a condition (true or false). IF tis true for g, record, then that record is considered in the query results. al Comparison Operators in WHERE Clause Condition © A condition must have some kind of comparison operator: Condition Meaning = Equal to < Less than > Greater than Less than or equal to (at most) Greater than or equal to (at least) Not equal IN Evaluates whether some S contained in a set of something else, © Comparison may be used in conjuction with Boolean Connectives: AND, OR and NOT Some Examples of WHERE, clause: © To find all employees who are married: SELECT * FROM Employee WHERE maritalStatus = ‘M’ ; Itcan be give'as SELECT * FROM Employee WHERE maritalStatus IN © To find all people who have the occupation of Electrician, Plumber, or Contractor: SELECT * FROM Employee WHERE occupation = ‘Electrician’ OR ‘occupation = ‘Plumber’ OR occupation = ‘Contractor’; The following query also gives the same results as above SELECT * FROM Employee WHERE occupation IN (‘Electrician ‘Plumber’, Contractor’) ; © To find all employees hired between 1990 and 1995 (inclusive). SELECT * FROM Employee WHERE yearHired > = 1990 AND yearklred < = 1995; GROUP BY Clause GROUP BY clause, asthe name indicated, divides the rows ofa table in smaller groups according to attribute specified after the GROUP BY clause in SELECT statement. It is used with SELECT statement Conditional retrieval of rows from within the selected group results can also be done using HAVING clause. To retrieve the grouped result in order. ORDER BY clause can also be used. The syntax of GROUP BY clause is 103 SELECT [DISTINCT] FROM [,
] [WHERE condition] GROUP BY [HAVING ] ample as ist ype and number of titles in each type, SELECT TextCat, COUNT (*) FROM Title GROUP BY Cat: List the above information sorted in ascending order of TextCat. SELECT TextCat, COUNT (TextCat) FROM Title GROUP BY TextCat ORDER BY TextCat HAVING Clause This clause is used to indicate which groups are to be displayed. Example List Ad, CopiesSold from Author-Title where CopiesSold is greater than or equal to 700 and sum is greater than 800. SELECT A#, SUM (CopiesSold) FROM Author-Title WHERE CopiesSold > 700 GROUP BY AR HAVING SUM (CopiesSold) > 800 We cannot use WHERE in place of HAVING to restrict rows selected using GROUP BY clause Output for the given query is List the above information in the ascending order of Sum of CopiesSold for all A# Select At, CopiesSold FROM Author_Title GROUP BY AH B ORDER BY CopiesSold | ‘tee “efault ORDER BY clause gives result in ascending order, so we have not mentioned anything ‘ifter “ Copiessold, It Ye Want result in descending order, we should put it as ORDER BY CopiesSold DESC 4,3. SUB-QUERIES 'A SELECT statement can be nested inside another select. The semantics is that the inner SEL E¢y generates values that are then consumed one-by-one by the outer SELECT. The simplest case is where ty, sinner SELECT produces a single tuple, with only one attribute (effectively a scalar value). In this casey. can use a standard comparison operation to compare an attribute value with the result of the inne, SELECT. Assume we have following two schema tables. : Emp (name, deptName, sales) DeptSales (deptName, itemSold, Cost) Which items are sold in Abhishek’s department? Following query will be executed/ SELECT itemSold FROM Deptsales WHERE deptName = (SELECT deptName FROM Emp WHERE name = ‘Abhishek’) ; ‘A more complicated case is where the inner SELECT produces a set of tuples, but each tuple has just a single attribute value. In thig case we can compare using one of the following keywords. © IN—trve if value exists in-result of sub-query © Comparison Operator ALL—true for comparison with every result © Comparison Operator ANY—true for comparison at least one result For example, to display the list of all names of employee who get salary more than everyone in marketing development? SELECT name FROM Emp WHERE salary > ALL (SELECT salary FROM Emp WHERE deptName = ‘Marketing’) ; We could determine who makes more salary than someone in marketing department by changing the ALL toan ANY. SELECT name | “FROM Emp WHERE salary > ANY (SELECT salary FROM Emp WHERE deptName = ‘Marketing’; -. » Again for example, to display the list of the names of people who sell “Laptop"? ong tt seLecT name FROM Emp WHERE deptName IN (SELECT deptName FROM deptsales WHERE itemSol ‘Laptop’ ) ; le value using scalar aggregate saoving 8108 .ds the names of titles whose price is lower than the current average price: ‘ye following query fin SELECT Titleld, Price FROM Title WHERE Price < (SELECT AVG(Price) FROM Title) Title ID Price 13 199 T4 100 Again, to list the Titleld and TName from table Title whose Price is maximum, year query should be: SELECT Titleld, Price FROM Title WHERE Price = (SELECT MAX (Price) FROM Author_Title) ‘Title ID Price Tl 399 12 299 Expression subqueries using group by and having clause 5 aqttezPression subqueries using the list of all the Titles whose price is lower than the lowest price of le whose TextCat = ‘PL’, For example, SELECT Thame from Title WHERE Price < (SELECT MIN (Price) from Title GROUP BY TextCat HAVING TextCat = ‘PL’) The atswer fortis is Subquery. 0 ar w , 2 ig Me have considered nested queries (e.g. subqueries which return only a sin; ions when more than one row is returned. To handle multirows comparisons, Petators 4 ne ‘ae available. Let us take an example. imple: List the names of authors from table Author whose A#fs are present in Author_Title Table. igle row), but there IN, ALL and ANY SELECT Aname FROM author WHERE AM IN (SELECT A# FROM Author_Title); ‘The subquery enclosed in parentheses returns multiple values of Ai. trou (207 199, 110, 120). The outer query returns the name of authors corresponding to these At Tom Fable Author. ithe beater is used instead of a relational operator. _ Titleld whose price is maximum in each TextCat eal Titleld, tname, TextCat FROM Title MERE Price IN (SELECT MAX (Price) FROM Title GROUP BY Here, TextCat); 112 Output Oracle ood Cc 299 PL TCPAP 250 Network Notes: 1 2. The inner query has to be enclosed in parentheses on the ri ight hand side of the condition ‘The subquery cannot have an ORDER BY clause inside it. It can be at the end of the main sy, Statement. 7 Subqueries are executed from the inner most nested to the least deeply nested Queries nes until they are correlated subqueries (discussed next), 4.3.1. Correlated Sub-Queries } and the result used in the query Ine led, for example. Find the items that are sold in two or more departments, ‘SELECT itemSold FROM dept D1 WHERE itemSold IN (SELECT itemSold FROM dept D2 WHERE D1. deptName < > 02 . deptName) ; Example: List all A3 who have Published more than one title. Use Author_Title table to count ho ‘many titles he has published as an inner query and use Author table te kroc the A#, Select Atl, Aname, Astatus FROM Author WHERE 1 < (SELECT COUNT (*) FROM AUTHOR_Title) WHERE A# = Author At) Output At Aname Astatus 100, Arora, 10 120, Basu 30 Example Show List of author names in whose title Discount is 10, SELECT Aft, Aname FROM Author WHERE EXISTS (SELECT Aq Fi ‘ROM Author Title, Title WHERE Discount=: 10 AND Title. Titleld = Author_Title. ANY Operator: This operator returns the lowest value of a set. We Example ...) Titleld) o Present two examples 113 ry vanguages Table Qualification qualification Astatus PhD. 10 M.Tech 20 B.Tech 30 MCA 30 Other 40 SELECT A# FROm Author WHERE Astatus DANY (SELECT Astatus FROm Qualification) Output 110 120 4.4. INDEXES An index is a data structure that is stored on disk that quickly maps keys to values. An index is just like a phone book. A phone book is organized in such a way that we can quickly map a name to a phone number. If the phone book were not sorted then we would have to look through each record in the phone book to find the number corresponding to a name. But because it is sorted we can use a ‘tree-like’ search to find a number given a name. Note that the opposite search find a name corresponding to a given umber, still requires us to search record by record, that is, it is still slow. So an index is strictly a performance enhancing mechanism. Common data structures are hash-tables are B-trees. Indexes are not part of the SQL standard, but are supported in many database systems. Below is the Syntax of a typical statement to create an index for a set of attributes. CREATE INDEX ON (attribute list>) Creating an Index Assume we have the relation Student (name, address). We can only create an index for an attribute that Sis UNIQUE, so let’s assume that name is a key. To create an index for a Student relation on the name Mribute we would issue the following SQL statement. CREATE INDEX studentNameIndex ON Student (name) ; This statement would ereate on disk a data structure that permits a quick search for a student named ‘chan’ than would be supported if the indexes were absent. We can create several indexes for the same table. A Second Index on a Table Assume we often look for student names using their addresses. We Sn the address attribute of the Student relation. might also wish to create an index —e 114 CREATE INDEX studentAddressindex ON Student (address) ; might seem like a good idea to index every attribute for every relation. However, tented wisely; the index is a data structure that is separated from the data so it increases the storage i. for a relation. An index on a relation typically adds 5% to 20% of the size of the oF the original data Storage cost for that relation. Indexes also add some overhead to updating, deleting, inserting tuples in a relation, indexes sho Indexes can be removed when desire to use the following syntax. DROP INDEX Dropping the Address Index We decide that the second index, on address, is not being used; to conserve disk space we decide w remove it, DROP INDEX studentAddressindex ; A view is a virtual relation, whose contents are derived from already existing relations and it does nat exist in physical form. The contents of view are determined by executing a query based in any relational nd it does no form the part of database schema. Each time a view is referred to ,ts contents are derived from the relations on which itis based. A view can be used like any other relat queried, inserted into, deleted from, and joined with other relations or Views, ‘on update operations. These are very useful accessed frequently instead of complete dat ‘The CREATE VIEW command of SQL can be used for creating views. This command provides the Tame 10 the view and specifies the list of attributes and tuples to be included using a subquery. The syntax to create a view is given here. tion, which is, it can be though with sor : limitations 1 in the situations where only parts of relations are to be a. CREATE VIEW As ; For example, the command to cre and Language Book categories can CREATE VIEW BOOK_1 AS SELECT * FROM BOOK WHERE Category IN "Textbook, ‘Language Book’); ‘This command creates a view, named as BOOK_1, having details of books satisfying the conditions specified in WHERE clause. The view created like this consists ofall the attributes of BOOK relation: however, only selected attributes can also be included in the view and they can be given another name also. For example, consider the command given here, CREATE VIEW BOOK_2 (B_Code, B Title, 8 Category, 8 Price) ‘AS SELECT ISBN, Book title, Category, Price FROM BOOK WHERE Category IN ('TextbooK, ‘Language Book’) ; ate a view containing details of books which belong to Text-book be specified as ae ataietl 115 ‘command creates a view BOOK_2, which we from the relation BOOK with new names, __ and Pricey, Now queries can be performed on thes crvple. consider the commands given here. SELECT * FROM BOOK_1 ; Consists of the attributes, ISBN, Book-title, Category, namely, B_Code, B_Title, B_Category, and B_Price, © Views as they are performed on the other relations. pores SELECT * FROM BOOK_2 WHERE B Price > 30; SELECT B_Title, 8_Category FROM BOOK_2 | WHERE B_Price BETWEEN 30 and 50 ; Views can be based on more than one relation. For exam, of atsibutes Book_title, Category, Price and P_ID of BOt relation can be specified as CREATE VIEW BOOK_3 AS SELECT Book_title, Category, Price, BOOK . P_ID, Pname, State . FROM BOOK, PUBLISHER WHERE BOOK . P_ID = PUBLISHER . P_ID The views that are based on more than one rela views are inefficient as they are time consuming to ex the view definition, Since their contents are n they are referred to. iple, the command to create a view consisting OK relation, Pname and State of Publisher tion are said to be complex views. These types of. ‘ecute, especially if multiple queries are involved in not physically stored, they are executed each and every time END, ne ee 4.6.1. Triggers A tigger i a set of statements that are executed a 7 S a side effect of a modifica cnute databae integrity. Once, a tigger is entered imo the anenice ir becomes the nano execute the trigger whenever due to database modification ne specified preconditions for the eee ee te ae ions for the execution (@) Conditions for execution of trigger. (6) Actions when trigger is executed, Consider the following schema: EMP (E#, E_NAME, SALARY, Di) DEPT (D_NUMB, D_NAME, TOTAL_sAL) Where TOTAL-SAL represents the total salary of all employees in a department. Create a Trigger to automatically update TOTAL_SAL when an employee is transferred from one Department to anothet one, Trigger CREATE OR REPLACE TRIGGER adj_sall AFTER UPDATE OF Dit OIN EMP FOR EACH ROW BEGIN IF:OLD.D# IS NOT NULL THEN BEGIN UPDATE DEPT ‘SET TOTAL_SAL = TOTAL_SAL -:OLD.SALARY WHERE DEPT.D_NUMB =:0LD.D#; END END IF; IF:NEW.D# IS NOT NULL UPDATE DEPT SET TOTAL, SAL = TOTAL_SAL + ;NEW.SALARY ‘WHERE DEPT.D_NUMB =; DH; END END IF; END; 4.6.2. Cursors ym, It has four phases ‘A Cursor is a pointer associated with a work area ina PL/SQL prograi Declaration of a Cursor ‘A cursor is declared associated a’ with a SQL statement in the DECLARE section of PL/gqy ‘The general syntax of declaration is: DECLARE CURSOR cursor-name IS SELECT statement; At this stage, the SELECT statement is not executed. Opening a Cursor ‘The general syntax is: OPEN cursor-name; When a cursor is opened, its SELECT statement is execu! statement, is brought into the cursor or the work area. The data st set. The cursor points to the first row in the active set. ted. The data, retrieved by the SELECT fored in the work area is called active dats Fetching Data from a Cursor ‘A Fetch statement in PL/SQL is used to fetch the row currently being pointed by the cursor. Its general syntax is:- FETCH cursor-name INTO local-variables; Each time a Fetch statement is executed, the cursor moves to the next row in the active set. After the last row, it returns cursor-name %NOTFOUND to be true. Closing a Cursor After processing the data in the active set, a cursor is closed. CLOSE cursor-name; 4 Since, there is max limit of the number of cursors currently open, a cursor should be closed when it is lone with. 1. Consider the following schema: Emp (E#, E_Name, Salary, D#t) Dept (D#, D_Name, Total_sal, Merit) Write a Cursor to increase the salary by 50% , Salary FROM Em ‘eno Emp.E#TYPE; au Emp Where salary> 40000, | sal Emp.Salary TYPE; BEGIN | OPEN C1; IF C1%ISOPEN THEN Loop FETCH C11 into eno, sal; EXIT WHEN C1%NOTFOUND; UPDATE Emp Set Sal = . = Fi es 1p lary toed 1.5 WHERE E# = eno; A CLOSE C1: END IF: EXCEPTION WHEN INVALID_CURSOR THEN DBMS_OUTPUT.PUT_LINE (‘Invalid Cursor’); END; | 4.6.3. Introduction to Stored Procedures Just like any other procedural language, PL/S You can call these PROCEDURES from oth other client program). ‘QL has code fragments that are called PROCEDURES. ier code fragments, or directly from SQL*Plus (or some Before you begin to write do that. If you don’t (which ; administrator (oF ask the a You're the administrator - Procedures though, you need to verify that you have enough pris:leges to Probably means you're using a plain user account), then you need to login as cdministrator) to grant you access. To grant such privilege yourself (incase running Oracle on your own machine) you can do: GRANT CREATE PROCEDURE TO someusername; From that Point on, the user someusername will be allowed to create, drop, and functions, and replace procedures Procedures Procedures are code fragments that don’t normally return a value, but may have some outside effects lke updating tables). The general format of a procedure is: PROCEDURE procedure_name IS BEGIN Procedure_body END; Se, "d we idd on i the procedure, so you'd want to a . 2 ither creating or replacing a ies ee cone REPI Perea saa For example, to create (or replace) a HELLO proc« ye | to ‘Might do Something like this: CREATE OR REPLACE PROCEDURE HELLO IS 120 : i ___ Database Memgoner yy BEGIN DBMS_OUTPUT.PUT_LINE(‘Hello World’); END; : The above declares a HELLO procedure that just display ‘Hello World’. You ean run it as par g¢ code fragment, or inside other procedures (or functions). For example: BEGIN HELLO( ); ‘END; Or you can simply execute it in SQL*Plus by typing: CALL HELLO( ); General Format ‘The general format of a create procedure statement is this: (CREATE OR REPLACE PROCEDURE procedure_name (parameters) IS BEGIN procedure_body END; Where procedure_name can be any valid SQL name, parameters is alist of parameters to this procedure (we'll discuss them later), and procedure_body is various PL/SQL statements that make up the logic of the procedure. Parameters ‘The parameters (or arguments) are optional. You don’t have to specify anything (not even the parenthesis). For example, a sample procedure, which you no doubt have already seen: CREATE OR REPLACE PROCEDURE HELLOWORLD IS BEGIN DBMS_OUTPUT.PUT_LINE(‘Hello World!’); END; = ‘Never actually defines any parameters. What's the use of a procedure that doesn’t take any parameters and doesn’t return anything ? Well, you may be interested in the Procedure’s side effects, like in our case, ‘we're interested in our procedure displaying ‘Hello World!’ and nothing else. There may be many instances where you may want to just do something to the database, without any particular parameters wo watoat returning anything. " Anyway, this section is about parameters so let's talk about parameters, Parameters are defined in a similar way as in a CREATE TABLE statement, which is to how Variables are declared. You first specify the name of dal the variable, and then the type. For example: (N INT) Would setup some procedure to accept an INT variable named N. Writing a simple procedure (0 display a variable name, you can come up with something like this: CREATE OR REPLACE PROCEDURE DISP (N INT) 1S. BEGIN 121 DBMS_OUTPUT.PUT_LINE('N is’ || N); END; | pich if you call, will promptly display: Which i au> CALL DISPN(1234567891); Nis 1234567891. |so have multiple parameters. For example, you can accept A and B and display their sum you can al oduct. a CREATE OR REPLACE PROCEDURE DISP_AB (A INT, B INT) IS BEGIN DBMS_OUTPUT.PUT_LINE(‘A + B =" || (A +8); DBMS_OUTPUT.PUT_LINE(‘A * B =’ || (A * B)); END; Which when ran, displays something like (depending on the values you provide): SQL> CALL DISP_AB(17, 23); A+B=40 Ae 391 Biw, it should be noted that you can use any PL/SQL type as an argument. For example, VARCHAR and others are perfectly acceptable. For example: | CREATE OR REPLACE PROCEDURE DISP_NAME (NAME VARCHAR) IS BEGIN DBMS_OUTPUT.PUT_LINE(‘Hi’ || NAME || ‘I’); END; Which when called displays: SQL> CALL DISP_NAME(‘John Doe’); Hi John Doe! IN, OUT, IN OUT There are various different parameter Varieties (not types). For example, for the time being, we have only been giving the procedure data Via parameters. This is the default (IN). What we could also do is get data from the procedure, via an OUT parameter. To do that, we simply specify OUT in between the parameter name and its type. For example: CREATE OR REPLACE PROCEDURE SUM_AB (A INT, B INT, C OUT INT) IS BEGIN Ci A+B; END; Notice that the above code does not display the resulting sum, it just changes the value of the C fameter. Also notice the word OUT right after the declaration of C parameter name. Anyway, we will use a code fragment to call the procedure: DECLARE RINT; BEGIN SUM_AB(23, 29, R); os 122 Database Management Sy, “0 DBMS_OUTPUT.PUT_LINE(‘SUM IS:’ || R); END; Which when ran, displays: SUM IS: 52 Notice how we called the procedure with an argument to eventually retrieve the OUT result, There is also the other special way of passing parameters: IN OUT. What that means is that We first cq, read the parameter, then we can change it. For example, we can write a procedure that doubles a num, CREATE OR REPLACE PROCEDURE DOUBLEN (NIN OUT INT) IS BEGIN NeN*2; END; To run it, we also create a small code fragment: DECLARE RINT; BEGIN R DBMS_OUTPUT.PUT_LINE(’BEFORE CALL R IS:’ || R); DOUBLEN(R); DBMS_OUTPUT.PUT_LINE(AFTER CALL R IS:" |] R); END; Which when ran displays: ™ ‘BEFORE CALL RIS: 7 AFTER CALL IS: 14 Notice how this particular call first grabbed the value of a parameter, then set it in order to return the double of the value. r ‘You can generally intermix these various ways of passing parameters (along with various types). You can use these to setup return values from procedures, etc. Dropping Procedures If you are interested in getting rid of a procedure totally, you can DROP it. The general format of DROPis: DROP PROCEDURE procedure_name; That is all there isto stored procedures. We will do some practice exercises and more experimentation, but overall, that is all there is to them, 4.6.4, Functions Functions are special types of procedures that have the capability to return a value. It is a very shady question of when to use what, either functions or procedures. A good rule of thu is: if you are interested in the “results” of the code, then you use a function, and return those results. Ifo" are interested in the “side effects” (like table updates, etc.) and not about the “result” when you should use a procedure. Usually it doesn’t affect your code all that much if you use a procedure or a function: quory Languages 123 General Format ‘The general format of a function is Very similar to the ene ats general format of a procedure: FUNCTION function_name (functi + a (func 'on_params) RETURN return type Is function_body RETURN something _of_return_type; END; For example, to write a function that computes the sum of two numbers, you might do something like this; CREATE OR REPLACE FUNCTION ADD_TWO (A INT, BEGIN RETURN (A + B); END; To run it, we will write a small piece of code that calls this: BEGIN OBMS_OUTPUT.PUT_LINE(‘RESULT IS:’ || ADD_TWO(12,34)); END; Which procudes the output: 8 INT) RETURN INT IS RESULT IS: 46 : All of a sudden, we know how to make functions (since we already know how to create procedures), ‘That is really there is to it. Dropping Functions To drop a function, you do it in a similar way to a procedure. You simply say: DROP FUNCTION function_name; Ob, btw, to display the list of procedures/functions or plain general user objects that you have you can run a query: SELECT OBJECT_NAME FROM USER_OBJECTS i WHERE OBJECT_TYPE = ‘FUNCTION’ ©u-can do a similar thing for procedures.

You might also like