Subject Name: DATABASE MANAGEMENT SYSTEM Subject Code: 10CS54

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 9 Introduction to SQL Programming Techniques.
CSC343 – Introduction to databases – A. Vaisman1 Database Application Development.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Objective: To access a database from an application program (as opposed to interactive interfaces) Why? An interactive interface is convenient but not.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
METU Department of Computer Eng Ceng 302 Introduction to DBMS SQL: Assertions, Views, and Programming Techniques by Pinar Senkul resources: mostly froom.
SPRING 2004CENG 3521 SQL: Constraints, Triggers, Embedded SQL Chapters: 5, 6.
Dec 11, 2003Murali Mani SQL with other Programming Languages B term 2004: lecture 16.
Database Systems More SQL Database Design -- More SQL1.
Chapter 9 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Advanced Database CS-426 Week 2 – Logic Query Languages, Object Model.
Chapter 9 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
Announcements Read JDBC Project Step 5, due Monday.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 9- 1 DATADABASE PROGRAMMING 2Chapter 13 from our text.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Lecture # 11 July 12,2012 More SQL: Complex Queries, Triggers,
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Announcements Written Homework 1 due Friday –If you have fourth edition make sure you do the right problems Program 3 out today, due next Friday Nov 10.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
Chapter 6 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
Chapter 7 SQL HUANG XUEHUA. AGGREGATE FUNCTIONS Include COUNT, SUM, MAX, MIN, and AVG Query 15: Find the maximum salary, the minimum salary, and the.
Advanced SQL: Triggers & Assertions
1 CS 430 Database Theory Winter 2005 Lecture 14: Additional SQL Topics.
Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.
Slide 8- 1 THE HAVING-CLAUSE Provides a condition on the summary information Sometimes we want to retrieve the values of these functions for only those.
DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 1.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 & 9 SQL-99: SchemaDefinition, Constraints, Introduction to SQL Programming Techniques.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
Chapter 7 SQL HUANG XUEHUA. Chapter Objectives Specification of more general constraints via assertions SQL facilities for defining views (virtual.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Database Application Development Database Programming Embedded SQL Dynamic SQL Embedded SQL in Java Database APIs: Alternative to embedding Embedded SQL.
SQL- Updates, Assertions and Views. Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations)
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Application Development Chapter 6.
Structured Query Language (3) The main reference of this presentation is the textbook and PPT from : Elmasri & Navathe, Fundamental of Database Systems,
10/3/2017.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
The SQL Database Grammar
Introduction to SQL Programming Techniques
SQL Environment.
Chapter 4 Basic SQL.
CS580 Advanced Database Topics
Views, Stored Procedures, Functions, and Triggers
Chapter 5: Advanced SQL Database System concepts,6th Ed.
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
Subject Name: DATA BASE MANAGEMENT SYSTEM Subject Code: 10cs54
More SQL: Complex Queries, Triggers, Views, and Schema Modification
11/9/2018.
CPSC-310 Database Systems
Database Application Development
DB Programming: SQL Programming Techniques
Introduction to SQL Programming Techniques
Unit I-2.
Structured Query Language (3)
SQL-99: Schema Definition, Constraints, and Queries and Views
Chapter 8 Advanced SQL.
Session - 6 Sequence - 5 SQL Updating Database Contents
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
SQL Updating Database Contents Presented by: Dr. Samir Tartir
SQL Views Presented by: Dr. Samir Tartir
Presentation transcript:

Subject Name: DATABASE MANAGEMENT SYSTEM Subject Code: 10CS54 Prepared By: NEENU RAJU Department: IS Date:10/8/14 9/18/2018

INSERT , DELETE AND UPDATE STATEMENTS IN SQL There are three SQL commands to modify the database: INSERT, DELETE, UPDATE 9/18/2018

INSERT In its simplest form, it is used to add one or more tuples to a relation Attribute values should be listed in the same order as the attributes were specified in the CREATE TABLE command 01/08/2014

INSERT (contd.) Example: U1: INSERT INTO EMPLOYEE VALUES ('Richard','K','Marini', '653298653', '30-DEC-52', '98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4 ) An alternate form of INSERT specifies explicitly the attribute names that correspond to the values in the new tuple Attributes with NULL values can be left out Example: Insert a tuple for a new EMPLOYEE for whom we only know the FNAME, LNAME, and SSN attributes. U1A: INSERT INTO EMPLOYEE (FNAME, LNAME, SSN) VALUES ('Richard', 'Marini', '653298653') 01/08/2014

INSERT (contd.) Important Note: Only the constraints specified in the DDL commands are automatically enforced by the DBMS when updates are applied to the database Another variation of INSERT allows insertion of multiple tuples resulting from a query into a relation 01/08/2014

INSERT (contd.) Example: Suppose we want to create a temporary table that has the name, number of employees, and total salaries for each department. A table DEPTS_INFO is created by U3A, and is loaded with the summary information retrieved from the database by the query in U3B. U3A: CREATE TABLE DEPTS_INFO (DEPT_NAME VARCHAR(10), NO_OF_EMPS INTEGER, TOTAL_SAL INTEGER); U3B: INSERT INTO DEPTS_INFO (DEPT_NAME,NO_OF_EMPS, TOTAL_SAL) SELECT DNAME, COUNT (*), SUM SALARY) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO GROUP BY DNAME ; 01/08/2014

INSERT (contd.) Note: The DEPTS_INFO table may not be up-to-date if we change the tuples in either the DEPARTMENT or the EMPLOYEE relations after issuing U3B. We have to create a view (see later) to keep such a table up to date. 01/08/2014

DELETE Removes tuples from a relation Includes a WHERE-clause to select the tuples to be deleted Referential integrity should be enforced Tuples are deleted from only one table at a time (unless CASCADE is specified on a referential integrity constraint) A missing WHERE-clause specifies that all tuples in the relation are to be deleted; the table then becomes an empty table The number of tuples deleted depends on the number of tuples in the relation that satisfy the WHERE-clause 01/08/2014

DELETE (contd.) Examples: U4A: DELETE FROM EMPLOYEE WHERE LNAME='Brown’ U4B: DELETE FROM EMPLOYEE WHERE SSN='123456789’ U4C: DELETE FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research') U4D: DELETE FROM EMPLOYEE 01/08/2014

UPDATE Used to modify attribute values of one or more selected tuples A WHERE-clause selects the tuples to be modified An additional SET-clause specifies the attributes to be modified and their new values Each command modifies tuples in the same relation Referential integrity should be enforced 01/08/2014

UPDATE (contd.) Example: Change the location and controlling department number of project number 10 to 'Bellaire' and 5, respectively. U5: UPDATE PROJECT SET PLOCATION = 'Bellaire', DNUM = 5 WHERE PNUMBER=10 01/08/2014

UPDATE (contd.) Example: Give all employees in the 'Research' department a 10% raise in salary. U6: UPDATE EMPLOYEE SET SALARY = SALARY *1.1 WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research') In this request, the modified SALARY value depends on the original SALARY value in each tuple The reference to the SALARY attribute on the right of = refers to the old SALARY value before modification The reference to the SALARY attribute on the left of = refers to the new SALARY value after modification 01/08/2014

Recap of SQL Queries A query in SQL can consist of up to six clauses, but only the first two, SELECT and FROM, are mandatory. The clauses are specified in the following order: SELECT <attribute list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attribute(s)>] [HAVING <group condition>] [ORDER BY <attribute list>] There are three SQL commands to modify the database: INSERT, DELETE, and UPDATE 01/08/2014

Constraints as Assertions General constraints: constraints that do not fit in the basic SQL categories (presented in chapter 8) Mechanism: CREAT ASSERTION Components include: a constraint name, followed by CHECK, followed by a condition 9/18/2018

Assertions: An Example “The salary of an employee must not be greater than the salary of the manager of the department that the employee works for’’ CREAT ASSERTION SALARY_CONSTRAINT CHECK (NOT EXISTS (SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE E.SALARY > M.SALARY AND E.DNO=D.NUMBER AND D.MGRSSN=M.SSN)) constraint name, CHECK, condition 9/18/2018

Using General Assertions Specify a query that violates the condition; include inside a NOT EXISTS clause Query result must be empty if the query result is not empty, the assertion has been violated 9/18/2018

SQL Triggers Objective: to monitor a database and take initiate action when a condition occurs Triggers are expressed in a syntax similar to assertions and include the following: Event Such as an insert, deleted, or update operation Condition Action To be taken when the condition is satisfied 9/18/2018

SQL Triggers: An Example A trigger to compare an employee’s salary to his/her supervisor during insert or update operations: CREATE TRIGGER INFORM_SUPERVISOR BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN ON EMPLOYEE FOR EACH ROW WHEN (NEW.SALARY> (SELECT SALARY FROM EMPLOYEE WHERE SSN=NEW.SUPERVISOR_SSN)) INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN); 9/18/2018

Views in SQL A view is a “virtual” table that is derived from other tables Allows for limited update operations Since the table may not physically be stored Allows full query operations A convenience for expressing certain operations 9/18/2018

Specification of Views SQL command: CREATE VIEW a table (view) name a possible list of attribute names (for example, when arithmetic operations are specified or when we want the names to be different from the attributes in the base relations) a query to specify the table contents 9/18/2018

SQL Views: An Example Specify a different WORKS_ON table CREATE VIEW WORKS_ON_NEW AS SELECT FNAME, LNAME, PNAME, HOURS FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER GROUP BY PNAME; 9/18/2018

Using a Virtual Table We can specify SQL queries on a newly create table (view): SELECT FNAME, LNAME FROM WORKS_ON_NEW WHERE PNAME=‘Seena’; When no longer needed, a view can be dropped: DROP WORKS_ON_NEW; 9/18/2018

Efficient View Implementation Query modification: Present the view query in terms of a query on the underlying base tables Disadvantage: Inefficient for views defined via complex queries Especially if additional queries are to be applied to the view within a short time period 9/18/2018

Efficient View Implementation View materialization: Involves physically creating and keeping a temporary table Assumption: Other queries on the view will follow Concerns: Maintaining correspondence between the base table and the view when the base table is updated Strategy: Incremental update 9/18/2018

Update Views Update on a single view without aggregate operations: Update may map to an update on the underlying base table Views involving joins: An update may map to an update on the underlying base relations Not always possible 9/18/2018

Un-updatable Views Views defined using groups and aggregate functions are not updateable Views defined on multiple tables using joins are generally not updateable WITH CHECK OPTION: must be added to the definition of a view if the view is to be updated To allow check for updatability and to plan for an execution strategy 9/18/2018

Database Programming Objective: Why? To access a database from an application program (as opposed to interactive interfaces) Why? An interactive interface is convenient but not sufficient A majority of database operations are made thru application programs (increasingly thru web applications) 9/18/2018

Database Programming Approaches Embedded commands: Database commands are embedded in a general-purpose programming language Library of database functions: Available to the host language for database calls; known as an API API standards for Application Program Interface A brand new, full-fledged language Minimizes impedance mismatch 9/18/2018

Impedance Mismatch Incompatibilities between a host programming language and the database model, e.g., type mismatch and incompatibilities; requires a new binding for each language set vs. record-at-a-time processing need special iterators to loop over query results and manipulate individual values 9/18/2018

Steps in Database Programming Client program opens a connection to the database server Client program submits queries to and/or updates the database When database access is no longer needed, client program closes (terminates) the connection 9/18/2018

Embedded SQL Most SQL statements can be embedded in a general-purpose host programming language such as COBOL, C, Java An embedded SQL statement is distinguished from the host language statements by enclosing it between EXEC SQL or EXEC SQL BEGIN and a matching END-EXEC or EXEC SQL END (or semicolon) Syntax may vary with language Shared variables (used in both languages) usually prefixed with a colon (:) in SQL 9/18/2018

Example: Variable Declaration in Language C Variables inside DECLARE are shared and can appear (while prefixed by a colon) in SQL statements SQLCODE is used to communicate errors/exceptions between the database and the program int loop; EXEC SQL BEGIN DECLARE SECTION; varchar dname[16], fname[16], …; char ssn[10], bdate[11], …; int dno, dnumber, SQLCODE, …; EXEC SQL END DECLARE SECTION; 9/18/2018

SQL Commands for Connecting to a Database Connection (multiple connections are possible but only one is active) CONNECT TO server-name AS connection-name AUTHORIZATION user-account-info; Change from an active connection to another one SET CONNECTION connection-name; Disconnection DISCONNECT connection-name; 9/18/2018

Embedded SQL in C Programming Examples loop = 1; while (loop) { prompt (“Enter SSN: “, ssn); EXEC SQL select FNAME, LNAME, ADDRESS, SALARY into :fname, :lname, :address, :salary from EMPLOYEE where SSN == :ssn; if (SQLCODE == 0) printf(fname, …); else printf(“SSN does not exist: “, ssn); prompt(“More SSN? (1=yes, 0=no): “, loop); END-EXEC } 9/18/2018

Embedded SQL in C Programming Examples A cursor (iterator) is needed to process multiple tuples FETCH commands move the cursor to the next tuple CLOSE CURSOR indicates that the processing of query results has been completed 9/18/2018

Dynamic SQL Objective: Composing and executing new (not previously compiled) SQL statements at run-time a program accepts SQL statements from the keyboard at run-time a point-and-click operation translates to certain SQL query Dynamic update is relatively simple; dynamic query can be complex because the type and number of retrieved attributes are unknown at compile time 9/18/2018

Dynamic SQL: An Example EXEC SQL BEGIN DECLARE SECTION; varchar sqlupdatestring[256]; EXEC SQL END DECLARE SECTION; … prompt (“Enter update command:“, sqlupdatestring); EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring; EXEC SQL EXECUTE sqlcommand; 9/18/2018

Embedded SQL in Java SQLJ: a standard for embedding SQL in Java An SQLJ translator converts SQL statements into Java These are executed thru the JDBC interface Certain classes have to be imported E.g., java.sql 9/18/2018

Java Database Connectivity JDBC: SQL connection function calls for Java programming A Java program with JDBC functions can access any relational DBMS that has a JDBC driver JDBC allows a program to connect to several databases (known as data sources) 9/18/2018

Steps in JDBC Database Access Import JDBC library (java.sql.*) Load JDBC driver: Class.forname(“oracle.jdbc.driver.OracleDriver”) Define appropriate variables Create a connect object (via getConnection) Create a statement object from the Statement class: 1. PreparedStatment 2. CallableStatement Identify statement parameters (designated by question marks) Bound parameters to program variables Execute SQL statement (referenced by an object) via JDBC’s executeQuery Process query results (returned in an object of type ResultSet) ResultSet is a 2-dimentional table 9/18/2018

Embedded SQL in Java: An Example ssn = readEntry("Enter a SSN: "); try { #sql{select FNAME< LNAME, ADDRESS, SALARY into :fname, :lname, :address, :salary from EMPLOYEE where SSN = :ssn}; } catch (SQLException se) { System.out.println("SSN does not exist: ",+ssn); return; System.out.println(fname + " " + lname + … ); 9/18/2018

Multiple Tuples in SQLJ SQLJ supports two types of iterators: named iterator: associated with a query result positional iterator: lists only attribute types in a query result A FETCH operation retrieves the next tuple in a query result: fetch iterator-variable into program-variable 9/18/2018

Database Programming with Functional Calls Embedded SQL provides static database programming API: Dynamic database programming with a library of functions Advantage: No preprocessor needed (thus more flexible) Disadvantage: SQL syntax checks to be done at run-time 9/18/2018

SQL Call Level Interface A part of the SQL standard Provides easy access to several databases within the same program Certain libraries (e.g., sqlcli.h for C) have to be installed and available SQL statements are dynamically created and passed as string parameters in the calls 9/18/2018

Components of SQL/CLI Environment record: Connection record: Keeps track of database connections Connection record: Keep tracks of info needed for a particular connection Statement record: Keeps track of info needed for one SQL statement Description record: Keeps track of tuples 9/18/2018

Steps in C and SQL/CLI Programming Load SQL/CLI libraries Declare record handle variables for the above components (called: SQLHSTMT, SQLHDBC, SQLHENV, SQLHDEC) Set up an environment record using SQLAllocHandle Set up a connection record using SQLAllocHandle Set up a statement record using SQLAllocHandle Prepare a statement using SQL/CLI function SQLPrepare Bound parameters to program variables Execute SQL statement via SQLExecute Bound query columns to a C variable via SQLBindCol Use SQLFetch to retrieve column values into C variables 9/18/2018

Database Stored Procedures Persistent procedures/functions (modules) are stored locally and executed by the database server As opposed to execution by clients Advantages: If the procedure is needed by many applications, it can be invoked by any of them (thus reduce duplications) Execution by the server reduces communication costs Enhance the modeling power of views Disadvantages: Every DBMS has its own syntax and this can make the system less portable 9/18/2018

Stored Procedure Constructs A stored procedure CREATE PROCEDURE procedure-name (params) local-declarations procedure-body; A stored function CREATE FUNCTION fun-name (params) RETRUNS return-type function-body; Calling a procedure or function CALL procedure-name/fun-name (arguments); 9/18/2018

SQL Persistent Stored Modules SQL/PSM: Part of the SQL standard for writing persistent stored modules SQL + stored procedures/functions + additional programming constructs E.g., branching and looping statements Enhance the power of SQL 9/18/2018

SQL/PSM: An Example CREATE FUNCTION DEPT_SIZE (IN deptno INTEGER) RETURNS VARCHAR[7] DECLARE TOT_EMPS INTEGER; SELECT COUNT (*) INTO TOT_EMPS FROM SELECT EMPLOYEE WHERE DNO = deptno; IF TOT_EMPS > 100 THEN RETURN “HUGE” ELSEIF TOT_EMPS > 50 THEN RETURN “LARGE” ELSEIF TOT_EMPS > 30 THEN RETURN “MEDIUM” ELSE RETURN “SMALL” ENDIF; 9/18/2018

Summary Assertions provide a means to specify additional constraints Triggers are assertions that define actions to be automatically taken when certain conditions occur Views create temporary (virtual) tables A database may be accessed in an interactive mode Most often, however, data in a database is manipulate via application programs Several methods of database programming: Embedded SQL Dynamic SQL Stored procedure and function 9/18/2018