[Virtual Presenter] Chapter 1: Advanced SQL Database System Concepts, 7th Ed. ©Silberschatz, Korth and Sudarshan www.db-book.com See www.db-book.com for conditions on re-use.
[Audio] ©Silberschatz, Korth and Sudarshan 1.2 Database System Concepts - 7th Edition.
[Audio] Procedural Constructs in SQL Compound statement begin … … End May contain multiple SQL statements between begin and end. Local variables can be declared within a compound statements begin declare d_count integer; select count (* ) into d_count from instructor where instructor.dept_name = dept_name return d_count; end ©Silberschatz, Korth and Sudarshan 1.3 Database System Concepts - 7th Edition.
[Audio] Loops While and repeat statements declare n integer default 0; while n < 10 do set n = n + 1 end while repeat set n = n – 1 until n = 0 end repeat For loop: Permits iteration over all results of a query declare n integer default 0; for r as select * from department do set n = n + r.budget end for ©Silberschatz, Korth and Sudarshan 1.4 Database System Concepts - 7th Edition.
[Audio] Conditional statements if-then-else if boolean expression then statement elseif boolean expression then statement …. else statement end if case statement similar to C case statement Signaling of exception conditions, and declaring handlers for exceptions declare out_of_classroom_seats condition declare exit handler for out_of_classroom_seats begin … .. signal out_of_classroom_seats end The handler here is exit -- causes enclosing begin ...end to be exited Other actions are possible on exception ©Silberschatz, Korth and Sudarshan 1.5 Database System Concepts - 7th Edition.
[Audio] Stored Procedures/Functions SQL:1999 supports functions and procedures called Stored Procedures Functions/Procedures can be written in SQL itself, or in an external programming language. Stored Procedures are Procedures stored in the database Stored Procedures permit external applications to operate on the database without knowing about internal details SQL:1999 also supports a rich set of imperative constructs, including Loops, if-then-else, assignment, … SQL:2003 added table-valued functions, which can return a relation as a result. Many databases have proprietary procedural extensions to SQL that differ from SQL:1999, 2003, and implement their own variant of the standard syntax. Read system manual to see what works on your system SQL:1999 allows overloading more than one function/procedure of the same name, as long as the number of arguments differ, or at least the types of the arguments differ. ©Silberschatz, Korth and Sudarshan 1.6 Database System Concepts - 7th Edition.
[Audio] SQL Functions Define a function that, given the name of a department, returns the count of the number of instructors in that department. create function dept_count (dept_name varchar(20)) returns integer begin declare d_count integer; select count (* ) into d_count from instructor where instructor.dept_name = dept_name return d_count; end The function dept_count can be used to find the department names and budget of all departments with more that 12 instructors. select dept_name, budget from department where dept_count (dept_name ) > 12 ©Silberschatz, Korth and Sudarshan 1.7 Database System Concepts - 7th Edition.
[Audio] Table Functions The SQL standard supports functions that can return tables as results; such functions are called table functions Example: Return all instructors in a given department create function instructor_of (dept_name char(20)) returns table ( ID varchar(5), name varchar(20), dept_name varchar(20), salary numeric(8,2)) return table (select ID, name, dept_name, salary from instructor where instructor.dept_name = instructor_of.dept_name) Usage select * from table (instructor_of ('Music')) ©Silberschatz, Korth and Sudarshan 1.8 Database System Concepts - 7th Edition.
[Audio] SQL Procedures The dept_count function could instead be written as procedure: create procedure dept_count_proc (in dept_name varchar(20), out d_count integer) begin select count(*) into d_count from instructor where instructor.dept_name = dept_count_proc.dept_name end The keywords in and out are parameters that are expected to have values assigned to them and parameters whose values are set in the procedure in order to return results. Procedures can be invoked either from an SQL procedure or from embedded SQL, using the call statement. declare d_count integer; call dept_count_proc( 'Physics', d_count); ©Silberschatz, Korth and Sudarshan 1.9 Database System Concepts - 7th Edition.
[Audio] External Language Functions & Procedures SQL allows us to define functions in a programming language such as Java, C#, C or C++. Can be more efficient than functions defined in SQL, and computations that cannot be carried out in SQL\can be executed by these functions. Declaring external language procedures and functions create procedure dept_count_proc(in dept_name varchar(20), out count integer) language C external name '/usr/avi/bin/dept_count_proc' create function dept_count(dept_name varchar(20)) returns integer language C external name '/usr/avi/bin/dept_count' ©Silberschatz, Korth and Sudarshan 1.10 Database System Concepts - 7th Edition.
[Audio] External Language Functions & Procedures Benefits of external language functions/procedures: more efficient for many operations, and more expressive power. Drawbacks Code to implement function may need to be loaded into database system and executed in the database system's address space. risk of accidental corruption of database structures security risk, allowing users access to unauthorized data There are alternatives, which give good security at the cost of potentially worse performance. Direct execution in the database system's space is used when efficiency is more important than security. ©Silberschatz, Korth and Sudarshan 1.11 Database System Concepts - 7th Edition.
[Audio] Security with External Language To deal with security problems, we can do on of the following: Use sandbox techniques That is, use a safe language like Java, which cannot be used to access/damage other parts of the database code. Run external language functions/procedures in a separate process, with no access to the database process' memory. Parameters and results communicated via inter-process communication Both have performance overheads Many database systems support both above approaches as well as direct executing in database system address space. ©Silberschatz, Korth and Sudarshan 1.12 Database System Concepts - 7th Edition.
[Audio] Triggers A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. To design a trigger mechanism, we must: Specify the conditions under which the trigger is to be executed. Specify the actions to be taken when the trigger executes. Triggers introduced to SQL standard in SQL:1999, but supported even earlier using non-standard syntax by most databases. Syntax illustrated here may not work exactly on your database system; check the system manuals ©Silberschatz, Korth and Sudarshan 1.13 Database System Concepts - 7th Edition.
[Audio] Triggering Events and Actions in SQL Triggering event can be insert, delete or update Triggers on update can be restricted to specific attributes For example, after update of takes on grade Values of attributes before and after an update can be referenced referencing old row as : for deletes and updates referencing new row as : for inserts and updates Triggers can be activated before an event, which can serve as extra constraints. For example, convert blank grades to null. create trigger setnull_trigger before update of takes referencing new row as nrow for each row when (nrow.grade = ' ') begin atomic set nrow.grade = null; end; ©Silberschatz, Korth and Sudarshan 1.14 Database System Concepts - 7th Edition.
[Audio] Trigger to Maintain credits_earned value create trigger credits_earned after update of takes on (grade) referencing new row as nrow referencing old row as orow for each row when nrow.grade <> 'F' and nrow.grade is not null and (orow.grade = 'F' or orow.grade is null) begin atomic update student set tot_cred= tot_cred + (select credits from course where course.course_id= nrow.course_id) where student.id = nrow.id; end; ©Silberschatz, Korth and Sudarshan 1.15 Database System Concepts - 7th Edition.
[Audio] Statement Level Triggers Instead of executing a separate action for each affected row, a single action can be executed for all rows affected by a transaction Use for each statement instead of for each row Use referencing old table or referencing new table to refer to temporary tables (called transition tables) containing the affected rows Can be more efficient when dealing with SQL statements that update a large number of rows ©Silberschatz, Korth and Sudarshan 1.16 Database System Concepts - 7th Edition.
[Audio] Statement Level Triggers example student_audit (date, user, action) create or replace trigger student_auditing after insert or update or delete on student declare action varchar2(50); begin If inserting then action := 'new emp record is add'; elsif updating then action := 'emp record is updated'; elsif deleting then action := 'emp record is deleted'; end if; insert into student_audit values (sysdate, user, action); end; ©Silberschatz, Korth and Sudarshan 1.17 Database System Concepts - 7th Edition.
[Audio] When Not To Use Triggers Triggers were used earlier for tasks such as maintaining summary data (e.g., total salary of each department) Replicating databases by recording changes to special relations and having a separate process that applies the changes over to a replica There are better ways of doing these now: Databases today provide built in materialized view to maintain summary data Databases today provide built-in support for replication Encapsulation facilities can be used instead of triggers in many cases Define methods to update fields and Carry out actions as part of the update methods instead of through a trigger Risk of unintended execution of triggers, for example, when loading data from a backup copy replicating updates at a remote site Trigger execution can be disabled before such actions. Other risks with triggers: Error leading to failure of critical transactions that set off the trigger Cascading execution ©Silberschatz, Korth and Sudarshan 1.18 Database System Concepts - 7th Edition.
[Audio] Accessing SQL from a Programming Language A database programmer must have access to a generalpurpose programming language for at least two reasons Not all queries can be expressed in SQL, since SQL does not provide the full expressive power of a general-purpose language. Non-declarative actions -- such as printing a report, interacting with a user, or sending the results of a query to a graphical user interface -- cannot be done from within SQL. There are two approaches to accessing SQL from a generalpurpose programming language Connect to and communicate with a database server using a collection of API (application-program interface) functions ODBC (Open Database Connectivity) works with C, C++, C#, and Visual Basic. Other API's such as ADO.NET sit on top of ODBC JDBC (Java Database Connectivity) works with Java Embedded SQL ©Silberschatz, Korth and Sudarshan 1.19 Database System Concepts - 7th Edition.
[Audio] ODBC Open DataBase Connectivity (ODBC) standard standard for application program to communicate with a database server. application program interface (API) to open a connection with a database, send queries and updates, get back results. ©Silberschatz, Korth and Sudarshan 1.20 Database System Concepts - 7th Edition.
[Audio] JDBC JDBC is a Java API for communicating with database systems supporting SQL. JDBC supports a variety of features for querying and updating data, and for retrieving query results. JDBC also supports metadata retrieval, such as querying about relations present in the database and the names and types of relation attributes. Model for communicating with the database: Open a connection Create a "statement" object Execute queries using the Statement object to send queries and fetch results Exception mechanism to handle errors ©Silberschatz, Korth and Sudarshan 1.21 Database System Concepts - 7th Edition.
[Audio] JDBC Code public static void JDBCexample(String dbid, String userid, String passwd) catch (SQLException sqle) } NOTE: Above syntax works with Java 7, and JDBC 4 onwards. Resources opened in "try (….)" syntax ("try with resources") are automatically closed at the end of the try block ©Silberschatz, Korth and Sudarshan 1.22 Database System Concepts - 7th Edition.
[Audio] JDBC Code (Cont.) Update to database try catch (SQLException sqle) Execute query and fetch and print results ResultSet rset = stmt.executeQuery( "select dept_name, avg (salary) from instructor group by dept_name"); while (rset.next()) ©Silberschatz, Korth and Sudarshan 1.23 Database System Concepts - 7th Edition.
[Audio] Prepared Statement PreparedStatement pStmt = conn.prepareStatement( "insert into instructor values(?,?,?,?)"); pStmt.setString(1, "88877"); pStmt.setString(2, "Perry"); pStmt.setString(3, "Finance"); pStmt.setInt(4, 125000); pStmt.executeUpdate(); pStmt.setString(1, "88878"); pStmt.executeUpdate(); WARNING: always use prepared statements when taking an input from the user and adding it to a query NEVER create a query by concatenating strings "insert into instructor values(' " + ID + " ', ' " + name + " ', " + " ' + dept name + " ', " ' balance + ')" What if name is "D'Souza"? ©Silberschatz, Korth and Sudarshan 1.24 Database System Concepts - 7th Edition.
[Audio] SQL Injection Suppose query is constructed using "select * from instructor where name = '" + name + "'" Suppose the user, instead of entering a name, enters: X' or 'Y' = 'Y then the resulting statement becomes: "select * from instructor where name = '" + "X' or 'Y' = 'Y" + "'" which is: select * from instructor where name = 'X' or 'Y' = 'Y' User could have even used X'; update instructor set salary = salary + 10000; - Prepared stament internally uses: "select * from instructor where name = 'X\' or \'Y\' = \'Y' Always use prepared statements, with user inputs as parameters ©Silberschatz, Korth and Sudarshan 1.25 Database System Concepts - 7th Edition.
[Audio] Metadata Features ResultSet metadata E.g.after executing query to get a ResultSet rs: ResultSetMetaData rsmd = rs.getMetaData(); for(int i = 1; i <= rsmd.getColumnCount(); i++) How is this useful? ©Silberschatz, Korth and Sudarshan 1.26 Database System Concepts - 7th Edition.
[Audio] Metadata (Cont) Database metadata DatabaseMetaData dbmd = conn.getMetaData(); // Arguments to getColumns: Catalog, Schema-pattern, Tablepattern, // and Column-Pattern // Returns: One row for each column; row has a number of attributes // such as COLUMN_NAME, TYPE_NAME // The value null indicates all Catalogs/Schemas. // The value "" indicates current catalog/schema // The value "%" has the same meaning as SQL like clause ResultSet rs = dbmd.getColumns(null, "univdb", "department", "%"); while( rs.next()) ©Silberschatz, Korth and Sudarshan 1.27 Database System Concepts - 7th Edition.
[Audio] Metadata (Cont) Database metadata DatabaseMetaData dbmd = conn.getMetaData(); // Arguments to getTables: Catalog, Schema-pattern, Table-pattern, // and Table-Type // Returns: One row for each table; row has a number of attributes // such as TABLE_NAME, TABLE_CAT, TABLE_TYPE, .. // The value null indicates all Catalogs/Schemas. // The value "" indicates current catalog/schema // The value "%" has the same meaning as SQL like clause // The last attribute is an array of types of tables to return. // TABLE means only regular tables ResultSet rs = dbmd.getTables ("", "", "%", new String[] ); while( rs.next()) And where is this useful? ©Silberschatz, Korth and Sudarshan 1.28 Database System Concepts - 7th Edition.
[Audio] Finding Primary Keys DatabaseMetaData dmd = connection.getMetaData(); // Arguments below are: Catalog, Schema, and Table // The value "" for Catalog/Schema indicates current catalog/schema // The value null indicates all catalogs/schemas ResultSet rs = dmd.getPrimaryKeys("", "", tableName); while(rs.next()) ©Silberschatz, Korth and Sudarshan 1.29 Database System Concepts - 7th Edition.
[Audio] Transaction Control in JDBC By default, each SQL statement is treated as a separate transaction that is committed automatically bad idea for transactions with multiple updates Can turn off automatic commit on a connection conn.setAutoCommit(false); Transactions must then be committed or rolled back explicitly conn.commit(); or conn.rollback(); conn.setAutoCommit(true) turns on automatic commit. ©Silberschatz, Korth and Sudarshan 1.30 Database System Concepts - 7th Edition.
[Audio] Other JDBC Features Calling functions and procedures CallableStatement cStmt1 = conn.prepareCall(""); CallableStatement cStmt2 = conn.prepareCall(""); Handling large object types getBlob() and getClob() that are similar to the getString() method, but return objects of type Blob and Clob, respectively get data from these objects by getBytes() associate an open stream with Java Blob or Clob object to update large objects blob.setBlob(int parameterIndex, InputStream inputStream). JDBC Basics Tutorial https://docs.oracle.com/javase/tutorial/jdbc/index.html ©Silberschatz, Korth and Sudarshan 1.31 Database System Concepts - 7th Edition.
[Audio] Embedded SQL The SQL standard defines embeddings of SQL in a variety of programming languages such as C, C++, Java, Fortran, and PL/1, A language to which SQL queries are embedded is referred to as a host language, and the SQL structures permitted in the host language comprise embedded SQL. The basic form of these languages follows that of the System R embedding of SQL into PL/1. EXEC SQL statement is used in the host language to identify embedded SQL request to the preprocessor EXEC SQL ; Note: this varies by language: In some languages, like COBOL, the semicolon is replaced with ENDEXEC In Java embedding uses # SQL ; ©Silberschatz, Korth and Sudarshan 1.32 Database System Concepts - 7th Edition.
[Audio] SQLJ JDBC is overly dynamic, errors cannot be caught by compiler SQLJ: embedded SQL in Java #sql iterator deptInfoIter ( String dept name, int avgSal); deptInfoIter iter = null; #sql iter = ; while (iter.next()) iter.close(); ©Silberschatz, Korth and Sudarshan 1.33 Database System Concepts - 7th Edition.
[Audio] Embedded SQL (Cont.) Before executing any SQL statements, the program must first connect to the database. This is done using: EXEC-SQL connect to server user user-name using password; Here, server identifies the server to which a connection is to be established. Variables of the host language can be used within embedded SQL statements. They are preceded by a colon (:) to distinguish from SQL variables (e.g., :credit_amount ) Variables used as above must be declared within DECLARE section, as illustrated below. The syntax for declaring the variables, however, follows the usual host language syntax. EXEC-SQL BEGIN DECLARE SECTION} int credit-amount ; EXEC-SQL END DECLARE SECTION; ©Silberschatz, Korth and Sudarshan 1.34 Database System Concepts - 7th Edition.
[Audio] Embedded SQL (Cont.) To write an embedded SQL query, we use the declare c cursor for statement. The variable c is used to identify the query Example: From within a host language, find the ID and name of students who have completed more than the number of credits stored in variable credit_amount in the host langue Specify the query in SQL as follows: EXEC SQL declare c cursor for select ID, name from student where tot_cred > :credit_amount END_EXEC ©Silberschatz, Korth and Sudarshan 1.35 Database System Concepts - 7th Edition.
[Audio] Embedded SQL (Cont.) The open statement for our example is as follows: EXEC SQL open c ; This statement causes the database system to execute the query and to save the results within a temporary relation. The query uses the value of the host-language variable credit-amount at the time the open statement is executed. The fetch statement causes the values of one tuple in the query result to be placed on host language variables. EXEC SQL fetch c into :si, :sn END_EXEC Repeated calls to fetch get successive tuples in the query result A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to '02000' to indicate no more data is available The close statement causes the database system to delete the temporary relation that holds the result of the query. EXEC SQL close c ; ©Silberschatz, Korth and Sudarshan 1.36 Database System Concepts - 7th Edition.
[Audio] Updates Through Embedded SQL Embedded SQL expressions for database modification (update, insert, and delete) Can update tuples fetched by cursor by declaring that the cursor is for update EXEC SQL declare c cursor for select * from instructor where dept_name = 'Music' for update We then iterate through the tuples by performing fetch operations on the cursor (as illustrated earlier), and after fetching each tuple we execute the following code: update instructor set salary = salary + 1000 where current of c ©Silberschatz, Korth and Sudarshan 1.37 Database System Concepts - 7th Edition.